"""Figures for journal note 27 (protocol 024, the two-signal decision rule), drawn only from the CSVs that
make_decisions_csv.py wrote from this package's results/decisions-a.json.

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

  1. decision-steps: the decision variable v of all 336 test steps of the six instances, by stimulus, against the
                     two thresholds.
  2. decision-relay: for the four plaids, each instance's mean v from the circuit and from the relay rule.

--font takes Latin Modern Roman font files (.ttf or .otf, or .woff if fontTools is installed). Without them the
figures fall back to STIXGeneral. It imports nothing but the standard library and matplotlib.
"""
import argparse, csv, 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'
T = 0.32
FOOT = ('Model: 2 mm reduction of LSV1M (Antolík et al. 2024, CC BY 4.0), simulated with Mozaik and NEST.\n'
        'Simulation only: an engineering rule on recorded model runs, no market signal and no action taken.')
ORDER = ['s8', 's10', 's11', 's12', 's13', 's14']
COLS = [('45@60', 'A 60'), ('45@15', 'A 15'), ('45@30+135@15', 'A 30\n+ B 15'), ('45@15+135@15', 'A 15\n+ B 15'),
        ('45@30+135@30', 'A 30\n+ B 30'), ('45@15+135@30', 'A 15\n+ B 30'), ('135@15', 'B 15'), ('135@60', 'B 60')]


def fonts(paths):
    family = []
    for p in paths:
        p = Path(p)
        if p.suffix.lower() == '.woff':
            from fontTools.ttLib import TTFont
            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-decisions-024', 'axes.edgecolor': LINE, 'axes.linewidth': 1,
                         'xtick.color': MUTED, 'ytick.color': MUTED, 'axes.labelcolor': MUTED})


def header(f, title, sub):
    f.text(.055, .94, 'felisyn  /  research note, protocol 024 (two-signal decision rule)', color=VIOLET, fontsize=15)
    f.text(.055, .872, title, fontsize=27)
    f.text(.055, .845, sub, color=MUTED, fontsize=14, va='top', linespacing=1.35)
    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 frame(ax):
    for side in ('top', 'right'):
        ax.spines[side].set_visible(False)
    ax.grid(axis='y', color=TINT, linewidth=1)
    ax.set_axisbelow(True)
    ax.axhspan(-T, T, color=TINT, zorder=0)
    for y in (-T, T):
        ax.axhline(y, color=MUTED, linewidth=1.2, linestyle=(0, (5, 4)))
    ax.axhline(0, color=LINE, linewidth=1)


def draw_steps(csv_dir, out):
    rows = [r for r in csv.DictReader(open(Path(csv_dir) / 'decision-steps.csv', newline='')) if r['role'] == 'test']
    assert len(rows) == 336
    f = plt.figure(figsize=(12.8, 8))
    ax = f.add_axes([.075, .14, .9, .52])
    frame(ax)
    for ci, (cond, _) in enumerate(COLS):
        for ii, inst in enumerate(ORDER):
            vs = [float(r['v']) for r in rows if r['condition'] == cond and r['instance'] == inst]
            x = ci + (ii - 2.5) * 0.11
            ax.plot([x] * len(vs), vs, 'o', markersize=4.2, color=VIOLET, alpha=.55, markeredgewidth=0)
    ax.set_xlim(-.6, len(COLS) - .4)
    ax.set_ylim(-1.7, 1.5)
    ax.set_xticks(range(len(COLS)))
    ax.set_xticklabels([l for _, l in COLS], fontsize=12.5)
    ax.tick_params(axis='x', length=0)
    ax.set_ylabel('decision variable v', fontsize=13)
    ax.text(len(COLS) - .45, T + .04, 'above: action B', ha='right', fontsize=12, color=MUTED)
    ax.text(len(COLS) - .45, -T - .11, 'below: action A', ha='right', fontsize=12, color=MUTED)
    ax.text(-.55, 0.05, 'between the lines: hold', fontsize=12, color=MUTED)
    header(f, 'Every test step fell on the intended side of the thresholds',
           'Signal A is a grating at 45°, signal B one at 135°; numbers are contrasts in percent. Each dot is one step; '
           'the six columns\nof dots per stimulus are the six network instances. Thresholds at ±0.32 were fixed on the '
           'pilot instance beforehand.\n336 of 336 steps took the intended action.')
    save(f, out, 'decision-steps')


def draw_relay(csv_dir, out):
    rows = list(csv.DictReader(open(Path(csv_dir) / 'decision-relay.csv', newline='')))
    plaids = [c for c in COLS if '+' in c[0]]
    f = plt.figure(figsize=(12.8, 8))
    ax = f.add_axes([.075, .14, .9, .50])
    frame(ax)
    for ci, (cond, _) in enumerate(plaids):
        for ii, inst in enumerate(ORDER):
            r = next(r for r in rows if r['plaid'] == cond and r['instance'] == inst)
            x = ci + (ii - 2.5) * 0.1
            vc, vr = float(r['v_circuit_mean']), float(r['v_relay'])
            ax.plot([x, x], [vr, vc], color=LINE, linewidth=1.2, zorder=2)
            ax.plot([x], [vc], 'o', markersize=7, color=VIOLET, zorder=4)
            wrong = r['relay_action'] != r['intended']
            ax.plot([x], [vr], 'o', markersize=7, markerfacecolor=INK if wrong else PAPER, markeredgecolor=INK,
                    markeredgewidth=1.5, zorder=3)
    ax.set_xlim(-.6, len(plaids) - .4)
    ax.set_ylim(-1.1, 1.1)
    ax.set_xticks(range(len(plaids)))
    ax.set_xticklabels([l.replace('\n', ' ') + f"\nintended: {i}" for (_, l), i in zip(plaids, ['A', 'hold', 'hold', 'B'])], fontsize=12.5)
    ax.tick_params(axis='x', length=0)
    ax.set_ylabel('mean decision variable v', fontsize=13)
    handles = [Line2D([], [], marker='o', linestyle='', markersize=7, color=VIOLET, label='the circuit’s response to the plaid'),
               Line2D([], [], marker='o', linestyle='', markersize=7, markerfacecolor=PAPER, markeredgecolor=INK,
                      markeredgewidth=1.5, label='relay rule: sum of the two single responses'),
               Line2D([], [], marker='o', linestyle='', markersize=7, color=INK, label='relay rule on the wrong side')]
    f.legend(handles=handles, loc='upper left', bbox_to_anchor=(.052, .735), frameon=False, fontsize=12.5, ncol=3,
             handletextpad=.4, columnspacing=1.6, borderaxespad=0)
    header(f, 'A relay of the single responses would have erred in 5 of 24 cases',
           'For each plaid and each of the six instances: the mean decision variable of the circuit’s own response, '
           'and of the sum of its\nresponses to the two gratings alone. Same thresholds (±0.32). The relay rule holds '
           'four times where B is the stronger signal,\nand acts once on an equal plaid.')
    save(f, out, 'decision-relay')


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('csv_dir')
    ap.add_argument('--font', nargs='*', default=[])
    a = ap.parse_args()
    fonts(a.font)
    draw_steps(a.csv_dir, Path(a.csv_dir))
    draw_relay(a.csv_dir, Path(a.csv_dir))
