"""Figures for journal note 29 (protocol 026, decisions over three steps), drawn only from decision-blocks.csv.

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

  1. three-steps:   every block of the close cells (one signal 7.5 points ahead) and of the equal cells: v at the
                    first, second and third step and their mean, against the thresholds.
  2. step-tally:    close and clear blocks decided as intended when the rule reads the first step alone, the second,
                    the third, the mean of the first two, or the mean of all three (the declared rule).

--font takes Latin Modern Roman font files. Standard library and matplotlib only.
"""
import argparse, csv, tempfile
from pathlib import Path

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

PAPER, INK, MUTED, LINE, TINT = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf', '#efe9f7'
VIOLET, AMBER = '#5924d6', '#b8660a'
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 model runs, no market signal and no action taken.')


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-steps-026', 'axes.unicode_minus': False, '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 026 (decisions over three steps)', color=VIOLET, fontsize=15)
    f.text(.055, .872, title, fontsize=24)
    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 read(csv_dir):
    rows = list(csv.DictReader(open(Path(csv_dir) / 'decision-blocks.csv', newline='')))
    for r in rows:
        for k in ('a', 'b', 'v1', 'v2', 'v3', 'v_mean'):
            r[k] = float(r[k])
        r['toward'] = -1.0 if r['a'] > r['b'] else 1.0           # the sign that points to the stronger signal's side
    return rows


def draw_steps(rows, out):
    f = plt.figure(figsize=(12.8, 8))
    close = [r for r in rows if r['kind'] == 'close']
    equal = [r for r in rows if r['kind'] == 'equal']
    held = sum(r['action'] != r['intended'] for r in close)
    header(f, 'Three steps in a row, and their mean',
           f'Each line is one block: the same pair of signals shown three times. Left: the {len(close)} blocks where one signal is 7.5 points ahead;\n'
           f'v is turned so that up means toward the stronger signal. Right: the {len(equal)} blocks of equal signals. Dashed: the thresholds at 0.32.')
    for n, (group, title, sign) in enumerate(((close, 'one signal 7.5 points ahead', True), (equal, 'equal signals', False))):
        ax = f.add_axes([.075 + .47 * n, .165, .40, .535])
        ax.set_facecolor(PAPER)
        for r in group:
            s = r['toward'] if sign else 1.0
            ys = [s * r['v1'], s * r['v2'], s * r['v3']]
            ok = r['action'] == r['intended']
            col = VIOLET if ok else AMBER
            ax.plot([0, 1, 2], ys, color=col, lw=1, alpha=.35, zorder=2)
            ax.plot([3.2], [s * r['v_mean']], 'o', color=col, ms=6, alpha=.75, mec='none', zorder=3)
        for y in ((T,) if sign else (T, -T)):
            ax.axhline(y, color=INK, lw=1, ls=(0, (4, 3)), zorder=1)
        ax.axhline(0, color=LINE, lw=1, zorder=0)
        if not sign:
            ax.axhspan(-T, T, color=TINT, zorder=0)
        ax.set_xticks([0, 1, 2, 3.2])
        ax.set_xticklabels(['step 1', 'step 2', 'step 3', 'mean of three'])
        ax.set_xlim(-.35, 3.7)
        lo = min(-.15, min((s2 for r in group for s2 in ((r['toward'] if sign else 1.0) * r[k] for k in ('v1', 'v2', 'v3'))), default=0) - .08)
        hi = max(1.1 if sign else .5, max((s2 for r in group for s2 in ((r['toward'] if sign else 1.0) * r[k] for k in ('v1', 'v2', 'v3'))), default=0) + .08)
        ax.set_ylim(lo if sign else -max(abs(lo), hi), hi if sign else max(abs(lo), hi))
        ax.set_ylabel('v toward the stronger signal' if sign else 'v  (A side below, B side above)')
        ax.set_title(title, fontsize=15, color=INK, loc='left', pad=10)
        for sp in ('top', 'right'):
            ax.spines[sp].set_visible(False)
        ax.tick_params(length=0)
    wrong_eq = sum(r['action'] != 'hold' for r in equal)
    f.text(.075, .092, f'Violet: the block decided as intended ({len(close) - held} of {len(close)} close blocks, {len(equal) - wrong_eq} of {len(equal)} equal blocks). '
           f'Amber: it did not ({held + wrong_eq}).', fontsize=12.5, color=MUTED)
    save(f, out, 'three-steps')


def draw_tally(rows, out):
    f = plt.figure(figsize=(12.8, 8))
    header(f, 'Reading one step, two steps, or three',
           'Blocks decided as intended, by what the rule reads. Only the mean of all three steps was declared as the rule;\n'
           'the other readings are shown for comparison and come from the same runs.')
    names = [('action1', 'first step'), ('action2', 'second step'), ('action3', 'third step'), ('action_first_two', 'mean of first two'), ('action', 'mean of all three')]
    for n, kind in enumerate(('close', 'clear')):
        group = [r for r in rows if r['kind'] == kind]
        ax = f.add_axes([.075 + .47 * n, .14, .40, .55])
        ax.set_facecolor(PAPER)
        vals = [sum(r[k] == r['intended'] for r in group) for k, _ in names]
        bars = ax.bar(range(len(names)), vals, color=[LINE] * 4 + [VIOLET], width=.62, zorder=2)
        for b, v in zip(bars, vals):
            ax.text(b.get_x() + b.get_width() / 2, v + len(group) * .015, f'{v}', ha='center', fontsize=15, color=INK)
        ax.axhline(len(group), color=INK, lw=1, ls=(0, (4, 3)), zorder=1)
        ax.text(len(names) - .37, len(group), f'all {len(group)}', ha='left', va='center', fontsize=12, color=MUTED, clip_on=False)
        ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True))
        ax.set_xticks(range(len(names)))
        ax.set_xticklabels([n2.replace(' of ', ' of\n') if 'mean' in n2 else n2 for _, n2 in names], fontsize=12.5)
        ax.set_ylim(0, len(group) * 1.14)
        ax.set_xlim(-.6, len(names) - .4)
        ax.set_ylabel('blocks as intended')
        ax.set_title({'close': 'close blocks: one signal 7.5 points ahead', 'clear': 'clear blocks: one signal 15 or more ahead, or alone'}[kind],
                     fontsize=15, color=INK, loc='left', pad=10)
        for sp in ('top', 'right'):
            ax.spines[sp].set_visible(False)
        ax.tick_params(length=0)
    save(f, out, 'step-tally')


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('csv_dir')
    ap.add_argument('--font', nargs='*', default=[])
    a = ap.parse_args()
    fonts(a.font)
    rows = read(a.csv_dir)
    draw_steps(rows, Path(a.csv_dir))
    draw_tally(rows, Path(a.csv_dir))
    print('drew three-steps and step-tally from', len(rows), 'blocks')
