"""Figures for journal note 25 (protocol 023 revision 2, CONFIRMED), drawn only from the CSVs that
make_confirm_csv.py wrote from the published results files.

  python3 -B draw_confirm.py CSV_DIR [--font FILE ...]        (each figure 1920 x 1200 PNG, and SVG)

  1. confirm-primaries: the three declared measures: each panel shows the pilot's estimate (open marker), the six
                        instance estimates with their within-instance 95 % intervals, and their mean with its 95 % t
                        interval, against the relay value 0 and the declared margin 0.10.
  2. xos-instances:     XOS by instance, with the mean's 95 % t band and the pilot's value, on a closer scale.

--font takes Latin Modern Roman font files (.ttf or .otf, or .woff if fontTools is installed). Without them the
figures fall back to STIXGeneral. Every plotted number is read from the CSVs, whose maker recomputed the means and
t intervals from the instance estimates and checked them against the declared values. It imports nothing but the
standard library and matplotlib.
"""
import argparse, csv, sys, tempfile
from pathlib import Path

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

PAPER, INK, MUTED, LINE, TINT = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf', '#efe9f7'
VIOLET = '#5924d6'   # the site's accent; one series, so no categorical pairing to validate
FOOT = ('Model: 2 mm reduction of LSV1M (Antolík et al. 2024, CC BY 4.0), simulated with Mozaik and NEST. '
        'Simulation only, six fresh instances: not a biological measurement.')
TITLES = {'XOS': 'XOS\ncross-orientation suppression', 'Dc': 'Dc\ndominance at unequal contrasts',
          'ds': 'ds\nreadout shift, signal units'}


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-confirm-023r2', 'axes.edgecolor': LINE, 'axes.linewidth': 1,
                         'xtick.color': MUTED, 'ytick.color': MUTED, 'axes.labelcolor': MUTED})
    return family[0]


def header(f, title, sub):
    f.text(.055, .94, 'felisyn  /  research note, protocol 023 revision 2 (confirmatory plaids)', color=VIOLET,
           fontsize=15)
    f.text(.055, .872, title, fontsize=28)
    f.text(.055, .823, sub, color=MUTED, fontsize=14)
    f.text(.055, .014, FOOT, fontsize=11, color=MUTED)


def save(f, out, name):
    f.savefig(out / f'{name}.png', dpi=150, facecolor=PAPER)
    f.savefig(out / f'{name}.svg', facecolor=PAPER, metadata={'Date': None})
    plt.close(f)


def quiet(ax, keep=('bottom', 'left')):
    for side in ('top', 'right', 'left', 'bottom'):
        ax.spines[side].set_visible(side in keep)


def signed(x, d=3):
    return ('−' if x < 0 else '+') + f'{abs(x):.{d}f}'


def read(csv_dir):
    data = {m: {'instance': [], 'mean': None, 'pilot': None} for m in ('XOS', 'Dc', 'ds')}
    with open(Path(csv_dir) / 'confirm-primaries.csv', newline='') as fh:
        for row in csv.DictReader(fh):
            m, kind = row['measure'], row['kind']
            rec = (row['instance'], float(row['value']), float(row['lo95']), float(row['hi95']))
            if kind == 'instance':
                data[m]['instance'].append(rec)
            else:
                data[m][kind] = rec
    for m, d in data.items():
        if len(d['instance']) != 6 or d['mean'] is None or d['pilot'] is None:
            sys.exit(f'refused: the CSV does not hold six instances, a mean and a pilot for {m}')
    return data


def draw_primaries(data, out):
    f = plt.figure(figsize=(12.8, 8))
    axs = f.subplots(1, 3, sharey=True, gridspec_kw={'left': .075, 'right': .975, 'top': .66, 'bottom': .115,
                                                     'wspace': .12})
    xi = [0.36 + 0.09 * k for k in range(6)]        # the six instances, left to right in run order
    for ax, m in zip(axs, ('XOS', 'Dc', 'ds')):
        d = data[m]
        quiet(ax)
        ax.set_xlim(0, 1.3)
        ax.set_ylim(0, 0.9)
        ax.grid(axis='y', color=TINT, linewidth=1)
        ax.set_axisbelow(True)
        ax.axhline(0, color=INK, linewidth=1.2)
        ax.axhline(0.10, color=MUTED, linewidth=1.2, linestyle=(0, (5, 4)))
        p = d['pilot']
        ax.plot([0.14], [p[1]], 'o', markersize=9, markerfacecolor=PAPER, markeredgecolor=VIOLET,
                markeredgewidth=1.8, zorder=5)
        for (_, v, lo, hi), x in zip(d['instance'], xi):
            ax.plot([x, x], [lo, hi], color=VIOLET, linewidth=1, alpha=.55, zorder=3,
                    solid_capstyle='butt')
            ax.plot([x], [v], 'o', markersize=5.5, color=VIOLET, zorder=4)
        _, mv, mlo, mhi = d['mean']
        ax.plot([1.02, 1.02], [mlo, mhi], color=INK, linewidth=2.4, zorder=4, solid_capstyle='butt')
        ax.plot([1.02], [mv], 'D', markersize=8, color=INK, zorder=5)
        ax.annotate(signed(mv), (1.02, mv), textcoords='offset points', xytext=(9, -4.5), fontsize=13, color=INK)
        ax.set_xticks([0.14, 0.63, 1.02])
        ax.set_xticklabels(['pilot', 'six fresh instances', 'mean'])
        ax.tick_params(axis='x', length=0, labelsize=12.5)
        ax.set_title(TITLES[m], fontsize=15, pad=10)
    axs[0].set_ylabel('measure value (0 = relay)', fontsize=13)
    axs[0].annotate('declared margin 0.10', (0.03, 0.10), textcoords='offset points', xytext=(0, 6),
                    fontsize=12, color=MUTED)
    axs[0].annotate('relay 0', (0.03, 0), textcoords='offset points', xytext=(0, 6), fontsize=12, color=MUTED)
    handles = [Line2D([], [], marker='o', linestyle='', markersize=9, markerfacecolor=PAPER,
                      markeredgecolor=VIOLET, markeredgewidth=1.8, label='pilot, instance A (one instance)'),
               Line2D([], [], marker='o', linestyle='-', markersize=5.5, color=VIOLET, alpha=.8,
                      label='fresh instance, with its within-instance 95 % interval'),
               Line2D([], [], marker='D', linestyle='-', markersize=8, color=INK, linewidth=2.4,
                      label='mean of the six, with its 95 % t interval')]
    f.legend(handles=handles, loc='upper left', bbox_to_anchor=(.052, .80), frameon=False, fontsize=12.5,
             handletextpad=.6, borderaxespad=0, ncol=3, columnspacing=1.6)
    header(f, 'All six fresh instances cleared the margin on all three measures',
           'Protocol 023 revision 2: each instance analysed only after two runs with identical inputs agreed on '
           'every spike train.\nOne-sided t-tests over the six instances with Holm at family-wise 0.025: all three '
           'pass, and each mean lies at least the margin from 0.')
    save(f, out, 'confirm-primaries')


def draw_xos(data, out):
    inst = data['XOS']['instance']
    _, mv, mlo, mhi = data['XOS']['mean']
    _, pv, _, _ = data['XOS']['pilot']
    f = plt.figure(figsize=(12.8, 8))
    ax = f.subplots(1, 1, gridspec_kw={'left': .075, 'right': .975, 'top': .70, 'bottom': .115})
    quiet(ax)
    xs = list(range(6))
    ax.set_xlim(-0.6, 5.6)
    ax.set_ylim(0.50, 0.70)
    ax.grid(axis='y', color=TINT, linewidth=1)
    ax.set_axisbelow(True)
    ax.axhspan(mlo, mhi, color=TINT, zorder=1)
    ax.axhline(mv, color=VIOLET, linewidth=1.2, zorder=2)
    ax.annotate(f'mean {signed(mv)}, 95 % t interval {signed(mlo)} to {signed(mhi)}', (4.62, mhi),
                textcoords='offset points', xytext=(0, 5), fontsize=12.5, color=MUTED, ha='right')
    ax.axhline(pv, color=INK, linewidth=1.2, linestyle=(0, (5, 4)), zorder=2)
    ax.annotate(f'pilot, instance A ({signed(pv)})', (-0.5, pv), textcoords='offset points', xytext=(0, -16),
                fontsize=12.5, color=MUTED, ha='left')
    for x, (seed, v, lo, hi) in zip(xs, inst):
        ax.plot([x, x], [lo, hi], color=VIOLET, linewidth=1.6, alpha=.55, zorder=3, solid_capstyle='butt')
        ax.plot([x], [v], 'o', markersize=9, color=VIOLET, zorder=4)
        ax.annotate(signed(v), (x, v), textcoords='offset points', xytext=(10, 7), fontsize=12.5, color=INK)
    ax.set_xticks(xs)
    ax.set_xticklabels([f'seed {seed}' for seed, *_ in inst], fontsize=13)
    ax.tick_params(axis='x', length=0)
    ax.set_ylabel('XOS (0 = relay)', fontsize=13)
    header(f, 'Suppression was consistent across the six instances',
           'XOS by network instance, in run order, with within-instance 95 % intervals. The band is the '
           'mean’s 95 % t interval.\nThe axis starts at 0.50: the relay value 0 and the declared margin 0.10 '
           'lie far below every interval.')
    save(f, out, 'xos-instances')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('csv_dir')
    ap.add_argument('--font', action='append', default=[])
    a = ap.parse_args()
    fonts(a.font)
    out = Path(a.csv_dir)
    data = read(a.csv_dir)
    draw_primaries(data, out)
    draw_xos(data, out)
    print('confirm-primaries and xos-instances drawn (PNG and SVG)')


if __name__ == '__main__':
    main()
