"""Figure 1 of journal note 24: LGN X_OFF cell 2738 in protocol 023's run s7 and in exact repeats of its inputs.

  python3 draw_cell2738.py [--font FILE ...]          (1920 x 1200 PNG, and SVG, written beside this script)

Reads, from this script's folder:
  cell2738-trains.csv     spike times below 15,000 ms, written by make_cell2738_csv.py from retained records
  cell2738-summary.json   the re-sync time and the counts, written by the same script

Exploratory, after protocol 023 ended NOT INTERPRETABLE: it changes nothing in that outcome. Simulation only.
--font takes Latin Modern Roman font files (.ttf or .otf, or .woff if fontTools is installed), as in the earlier
notes' plotting code. Without them the figure falls back to STIXGeneral. The script stops if the two files disagree.
It imports nothing but the standard library and matplotlib.
"""
import argparse, csv, json, sys, tempfile
from pathlib import Path

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager

PAPER, INK, MUTED, LINE, WASH = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf', '#efe9f5'
VIOLET = '#5924d6'
ROWS = [('pilot_reference', 'Pilot reference', 'lead-in only'), ('s7', 's7', 'the protocol run, refused'),
        ('d5', 'd5', 'exact repeat'), ('rate_r1', 'rate-r1', 'exact repeat')]
FOOT = ('Model: 2 mm reduction of LSV1M (Antolík et al. 2024, CC BY 4.0), simulated with Mozaik and NEST. '
        'Simulation only: not a biological measurement.')


def fonts(paths):
    family = []
    for p in paths:
        p = Path(p)
        if p.suffix.lower() == '.woff':
            from fontTools.ttLib import TTFont   # optional: only to read the site's web font
            t = TTFont(str(p))
            t.flavor = None
            tmp = Path(tempfile.mkdtemp()) / (p.stem + '.ttf')
            t.save(str(tmp))
            p = tmp
        font_manager.fontManager.addfont(str(p))
        family.append(font_manager.FontProperties(fname=str(p)).get_name())
    family = list(dict.fromkeys(family)) + ['STIXGeneral']
    plt.rcParams.update({'font.family': family, 'text.color': INK, 'font.size': 14, 'svg.fonttype': 'none',
                         'svg.hashsalt': 'felisyn-note-24', 'axes.edgecolor': LINE, 'axes.linewidth': 1,
                         'xtick.color': MUTED, 'ytick.color': MUTED, 'axes.labelcolor': MUTED})


def load(here):
    trains = {k: [] for k, _, _ in ROWS}
    extra = []
    with open(here / 'cell2738-trains.csv', newline='') as fh:
        for r in csv.DictReader(fh):
            t = float(r['spike_ms']) / 1000
            trains[r['run']].append(t)
            if r['s7_no_d5_within_5ms'] == '1':
                extra.append(t)
    s = json.loads((here / 'cell2738-summary.json').read_text())
    lead = s['lead_ms'] / 1000
    for k in trains:
        if [round(t * 1000, 1) for t in trains[k] if t < lead] != s['lead_in'][k]:
            sys.exit(f'refused: the CSV and the summary disagree on the lead-in of {k}')
    if len(extra) != s['s7_spikes_without_d5_within_5ms'] or trains['rate_r1'] != trains['d5']:
        sys.exit('refused: the CSV and the summary disagree')
    return trains, extra, s


def raster(ax, trains, extra, x0, x1, tick_h=.62):
    ex = set(extra)
    for i, (k, _, _) in enumerate(ROWS):
        y = len(ROWS) - 1 - i
        ts = [t for t in trains[k] if x0 <= t <= x1]
        plain = [t for t in ts if t not in ex]
        hot = [t for t in ts if t in ex]
        ax.vlines(plain, y - tick_h / 2, y + tick_h / 2, color=INK, lw=1.1, zorder=3)
        if hot:   # s7 spikes with no d5 spike within 5 ms: violet and taller, so colour is not the only cue
            ax.vlines(hot, y - .46, y + .46, color=VIOLET, lw=1.8, zorder=4)
    ax.set_ylim(-.6, len(ROWS) - .4)
    ax.set_xlim(x0, x1)
    for side in ('top', 'right', 'left'):
        ax.spines[side].set_visible(False)
    ax.set_yticks([])
    ax.tick_params(length=0, labelsize=12, pad=6)


def draw(here):
    trains, extra, s = load(here)
    resync = s['resync_time_ms'] / 1000
    lead = s['lead_ms'] / 1000
    f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
    f.text(.055, .945, 'felisyn  /  research note 24 (protocol 023\'s early stop)', color=VIOLET, fontsize=15)
    f.text(.055, .878, 'Cell 2738 fired extra spikes in s7 until 14.3 s', fontsize=28)
    f.text(.055, .833, 'Spike times of one LGN OFF cell in the refused run s7 and in two exact repeats of its inputs. '
                       'Exploratory, after the outcome.', color=MUTED, fontsize=14)
    f.text(.055, .014, FOOT, fontsize=11, color=MUTED)

    # A: the first 15 s of the sequence
    a = f.add_axes([.215, .455, .755, .3], facecolor=PAPER)
    a.axvspan(0, lead, color=WASH, zorder=0, lw=0)
    raster(a, trains, extra, 0, 15)
    a.set_xticks(range(0, 16))
    a.set_xlabel('Seconds into the stimulus sequence', fontsize=13, labelpad=7)
    a.vlines(resync, -.6, len(ROWS) - .45, color=INK, lw=1.2, ls=(0, (5, 3)), zorder=2)
    a.text(resync - .08, len(ROWS) - .52, f'Equal again from\n{s["resync_time_ms"]:,.1f} ms', fontsize=12,
           ha='right', va='center', linespacing=1.1)
    for i, (k, name, note) in enumerate(ROWS):
        y = len(ROWS) - 1 - i
        f.text(.055, a.transData.transform((0, y))[1] / f.bbox.height, f'{name}', fontsize=14,
               va='center', transform=f.transFigure, color=VIOLET if k == 's7' else INK)
        f.text(.055, a.transData.transform((0, y - .32))[1] / f.bbox.height, note, fontsize=11.5,
               va='center', transform=f.transFigure, color=MUTED)
    per = s['per_1s_bin_d5_s7']
    a.text(-.06, len(ROWS) - .05, 's7 minus d5,\nper second:', fontsize=11, color=MUTED, ha='right', va='bottom',
           linespacing=1.05, transform=a.get_yaxis_transform())
    for k, (n5, n7) in enumerate(per):
        a.text(k + .5, len(ROWS) - .05, f'{n7 - n5:+d}', fontsize=12, ha='center', va='bottom',
               color=VIOLET if n7 > n5 else MUTED)
    a.set_ylim(-.6, len(ROWS) + .35)

    # B: the lead-in, the part the check compares
    b = f.add_axes([.215, .145, .33, .225], facecolor=PAPER)
    raster(b, trains, extra, 0, lead)
    b.set_xticks([0, .1, .2, .3, .4, .5])
    b.set_xticklabels(['0', '100', '200', '300', '400', '500'])
    b.set_xlabel('Milliseconds: the 504 ms lead-in the check compares', fontsize=13, labelpad=7)
    for i, (k, name, _) in enumerate(ROWS):
        y = len(ROWS) - 1 - i
        b.text(-.012, y, name, fontsize=12, ha='right', va='center', color=VIOLET if k == 's7' else INK)
    b.text(lead, len(ROWS) - 1, f'{len(s["lead_in"]["s7"])} spikes in s7,\n{len(s["lead_in"]["d5"])} in the others',
           fontsize=12, ha='right', va='center', color=MUTED, linespacing=1.1)

    # C: around the re-sync
    c = f.add_axes([.64, .145, .33, .225], facecolor=PAPER)
    lo, hi = resync - .45, resync + .35
    raster(c, trains, extra, lo, hi)
    c.axvline(resync, color=INK, lw=1.2, ls=(0, (5, 3)), zorder=2)
    ticks = [round(lo + .05, 1) + .1 * j for j in range(9) if lo <= round(lo + .05, 1) + .1 * j <= hi]
    c.set_xticks(ticks)
    c.set_xticklabels([f'{t:.1f}' for t in ticks])
    c.set_xlabel('Seconds: around the re-sync', fontsize=13, labelpad=7)
    for i, (k, name, _) in enumerate(ROWS[1:], start=1):
        y = len(ROWS) - 1 - i
        c.text(lo - .012, y, name, fontsize=12, ha='right', va='center', color=VIOLET if k == 's7' else INK)
    c.set_ylim(-.6, len(ROWS) - .9)   # the reference holds the lead-in only, so its row is left out here
    c.text(resync + .012, len(ROWS) - .95, 'identical from here', fontsize=12, ha='left', va='top', color=MUTED)

    f.text(.055, .045, f'Violet, taller ticks: the {len(extra)} s7 spikes with no d5 spike within 5 ms. Shaded: the '
                       'lead-in. d5 and rate-r1 are identical in every spike.', fontsize=12, color=MUTED)
    f.savefig(here / 'cell2738.png', dpi=150, facecolor=PAPER)
    f.savefig(here / 'cell2738.svg', facecolor=PAPER, metadata={'Date': None})
    plt.close(f)


if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('--font', nargs='*', default=[])
    a = p.parse_args()
    fonts(a.font)
    draw(Path(__file__).resolve().parent)
