"""Figures for protocol 017's results (controller-015 milestone 2), from the retained results only.
  1. OUT_STEM.png/.svg: each run's carry-over c with its 95 % bootstrap interval, the declared margin, and the
     error-null range of c (a relay whose errors are the run's own, redrawn independently within signal bins).
  2. OUT_STEM-signals.png/.svg: the decoded decision signal against the input signal, one panel per run.

  python3 draw_decisions.py RESULTS.json SEQUENCE.json LOG_DIR OUT_STEM      (1920 x 1200 each)

RESULTS.json is analyze_decisions.py's output; LOG_DIR holds its decisions-NAME.json logs.
"""
import json, math, sys, textwrap
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

PAPER, INK, MUTED, LINE = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf'
INTACT, LESION = '#6240ab', '#b26a00'          # the validated pair used in the earlier figures
BAND, NULL = '#d9cdee', '#cfc8d6'
plt.rcParams.update({'font.family': 'STIXGeneral', 'text.color': INK, 'font.size': 14, 'svg.fonttype': 'none',
                     'axes.edgecolor': LINE, 'xtick.color': MUTED, 'ytick.color': MUTED})
RUNS = ['intact-A', 'intact-B', 'feedforward-only']
LABEL = {'intact-A': 'intact, instance A', 'intact-B': 'intact, instance B', 'feedforward-only': 'feedforward only'}
NOTE = {'intact-A': 'published connectivity', 'intact-B': 'another random network instance',
        'feedforward-only': 'all 12 cortical projections off'}
FOOT = ('Model: 2 mm reduction of LSV1M (Antolík et al. 2024, CC BY 4.0), simulated with Mozaik and NEST. '
        'Simulation only: no token, wallet or real order.')

res = json.load(open(sys.argv[1]))
seq = json.load(open(sys.argv[2]))
logs, stem = Path(sys.argv[3]), sys.argv[4]
margin, pol = res['parameters']['margin'], res['policies']
colour = {r: LESION if r == 'feedforward-only' else INTACT for r in RUNS}
SHORT = {'intact-A': 'intact A', 'intact-B': 'intact B', 'feedforward-only': 'feedforward only'}


def signed(x):
    return f'{x:+.3f}'.replace('-', '\u2212')


def header(f, kicker, title, sub):
    f.text(.055, .94, kicker, color=INTACT, fontsize=15)
    f.text(.055, .872, title, fontsize=28)
    f.text(.055, .823, sub, color=MUTED, fontsize=14)
    f.text(.055, .025, FOOT, fontsize=11, color=MUTED)


# ---------------------------------------------------------------- figure 1: carry-over per run
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
header(f, 'felisyn  /  research note, protocol 017', 'Does the circuit carry the last input into its next decision?',
       'Carry-over c in  ŝ(t) = a + b·s(t) + c·s(t−1),  with 95% moving-block bootstrap intervals; '
       f"{res['n_steps']} steps per run.")
ax = f.add_axes([.27, .27, .41, .48], facecolor=PAPER)
xs = [-margin, margin]
lesion_key, lesion = next(iter(res['lesion'].items())) if res['lesion'] else (None, None)
for i, name in enumerate(RUNS):
    y, m = len(RUNS) - 1 - i, pol[name]
    lo, hi = m['error_null']['history_c_95']
    ax.plot([lo, hi], [y - .24, y - .24], color=NULL, lw=6, solid_capstyle='butt', zorder=1)
    ax.plot(m['history_c_95'], [y, y], color=colour[name], lw=2.2, solid_capstyle='round', zorder=3)
    ax.scatter([m['history_c']], [y], s=80, color=colour[name], edgecolors=PAPER, linewidths=2, zorder=4)
    xs += list(m['history_c_95']) + [lo, hi]
    yy = .27 + .48 * (y + .5) / len(RUNS)
    f.text(.255, yy + .012, LABEL[name], ha='right', va='center', fontsize=15)
    f.text(.255, yy - .025, NOTE[name], ha='right', va='center', fontsize=12, color=MUTED)
    f.text(.70, yy + .012, m['carry_over'], va='center', fontsize=14)
    f.text(.70, yy - .025, f"c {signed(m['history_c'])} · gain {m['gain_b']:.2f} · {100 * m['accuracy_vs_rule']:.0f}% match the rule",
           va='center', fontsize=12, color=MUTED)
    if lesion and name == lesion_key.split('|')[1]:
        dc = lesion['delta_c']
        f.text(.70, yy - .058, f"Δc ({SHORT[lesion_key.split('|')[0]]} − this) {signed(dc['estimate'])} "
                               f"[{signed(dc['ci95'][0])}, {signed(dc['ci95'][1])}]", va='center', fontsize=12, color=MUTED)
ax.axvspan(-margin, margin, color=BAND, alpha=.5, lw=0, zorder=0)
ax.axvline(0, color=MUTED, lw=1, zorder=.5)
lim = max(abs(x) for x in xs) * 1.2
ax.set_xlim(-lim, lim)
ax.set_ylim(-.65, len(RUNS) - .4)
ax.set_yticks([])
ax.set_xlabel('carry-over c (weight of the previous input in the decoded signal)', color=MUTED)
for s in ('top', 'right', 'left'):
    ax.spines[s].set_visible(False)
ax.grid(axis='x', color=LINE, lw=.6, alpha=.6)
f.text(.27, .175, f'Shaded: the declared margin of ±{margin:.2f}. Grey bars: c for a relay with the run\'s own errors (95% range). '
                  'Violet: intact; amber: lesion.', fontsize=12, color=MUTED)
r = res['readings']
f.text(.27, .135, f"Declared reading: {r['overall']}.", fontsize=14)
f.text(.27, .105, '\n'.join(textwrap.wrap(r['overall_text'], 120)), fontsize=12, color=MUTED, va='top')
for ext in ('png', 'svg'):
    f.savefig(f'{stem}.{ext}', facecolor=PAPER)
plt.close(f)

# ---------------------------------------------------------------- figure 2: decoded signal against the input
s = np.asarray(seq['signals'], float)
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
header(f, 'felisyn  /  research note, protocol 017', 'What the circuit passes on',
       'Decoded decision signal ŝ(t) against the input signal s(t) for every step; the dotted lines are the buy and sell '
       'thresholds.')
threshold = res['parameters']['threshold']
for k, name in enumerate(RUNS):
    log = json.load(open(logs / f'decisions-{name}.json'))['log']
    th = np.array([np.nan if e['model_output']['theta'] is None else e['model_output']['theta'] for e in log], float)
    s_hat = np.clip((th - math.pi / 2) / (math.pi / 4), -1.0, 1.0)
    ax = f.add_axes([.07 + k * .31, .2, .25, .52], facecolor=PAPER)
    ax.plot([-1, 1], [-1, 1], color=LINE, lw=1.2, zorder=0)
    for v in (-threshold, threshold):
        ax.axhline(v, color=MUTED, lw=.8, ls=(0, (1, 3)), zorder=0)
    ax.scatter(s, s_hat, s=22, color=colour[name], edgecolors=PAPER, linewidths=.6, zorder=2)
    ax.set_xlim(-1.08, 1.08)
    ax.set_ylim(-1.08, 1.08)
    ax.set_aspect('equal')
    ax.set_xticks([-1, -.5, 0, .5, 1])
    ax.set_yticks([-1, -.5, 0, .5, 1])
    ax.set_xlabel('input signal s(t)', color=MUTED)
    if k == 0:
        ax.set_ylabel('decoded signal ŝ(t)', color=MUTED)
    for sp in ('top', 'right'):
        ax.spines[sp].set_visible(False)
    m = pol[name]
    ax.set_title(f"{LABEL[name]}\nerror SD {m['error_sd_deg']:.1f}°; {100 * m['accuracy_vs_rule']:.0f}% match the rule",
                 fontsize=14, color=INK, pad=10)
for ext in ('png', 'svg'):
    f.savefig(f'{stem}-signals.{ext}', facecolor=PAPER)
plt.close(f)
