"""Figures for journal note 28 (protocol 025, the decision map), drawn only from decision-map.csv.

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

  1. decision-map:   one 5 x 5 grid per instance: each cell shows the mean decision variable v and the actions its
                     steps took; scored cells are outlined.
  2. decision-diff:  v against the difference of the two strengths (B minus A), every cell and instance, with the
                     thresholds: the shape of the transition.

--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
from matplotlib import font_manager
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.lines import Line2D

PAPER, INK, MUTED, LINE, TINT = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf', '#efe9f7'
VIOLET, AMBER = '#5924d6', '#b8660a'      # B side and A side of the diverging scale, through the paper colour
T = 0.32
STRENGTHS = [0.0, 7.5, 15.0, 22.5, 30.0]
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.')
CMAP = LinearSegmentedColormap.from_list('ab', [AMBER, PAPER, VIOLET])


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-map-025', '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 025 (decision map)', 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-map.csv', newline='')))
    for r in rows:
        for k in ('a', 'b', 'v_mean', 'v_min', 'v_max'):
            r[k] = float(r[k])
        for k in ('n', 'n_A', 'n_hold', 'n_B'):
            r[k] = int(r[k])
    return rows


def acts(r):
    parts = [f"{r[k]} {n}" for k, n in (('n_A', 'A'), ('n_hold', 'hold'), ('n_B', 'B')) if r[k]]
    return parts[0].split(' ', 1)[1] if len(parts) == 1 else ', '.join(parts)


def draw_map(rows, out, title, sub):
    inst = sorted({r['instance'] for r in rows}, key=lambda s: int(s[1:]))
    f = plt.figure(figsize=(12.8, 8))
    axs = f.subplots(1, len(inst), gridspec_kw={'left': .07, 'right': .985, 'top': .64, 'bottom': .13, 'wspace': .16})
    for ax, k in zip(axs, inst):
        ax.set_aspect('equal')
        for r in rows:
            if r['instance'] != k:
                continue
            x, y = STRENGTHS.index(r['b']), STRENGTHS.index(r['a'])
            v = max(-1.0, min(1.0, r['v_mean']))
            ax.add_patch(plt.Rectangle((x - .5, y - .5), 1, 1, facecolor=CMAP((v + 1) / 2), edgecolor=PAPER, linewidth=2))
            if r['role'] == 'scored':
                ax.add_patch(plt.Rectangle((x - .46, y - .46), .92, .92, fill=False, edgecolor=INK, linewidth=1.3))
            dark = abs(v) > 0.55
            ax.text(x, y + .13, ('0.00' if abs(r['v_mean']) < .005 else f"{r['v_mean']:+.2f}"), ha='center', va='center', fontsize=11.5,
                    color=PAPER if dark else INK)
            ax.text(x, y - .2, acts(r), ha='center', va='center', fontsize=8.6, color=PAPER if dark else MUTED)
        ax.set_xlim(-.5, 4.5)
        ax.set_ylim(-.5, 4.5)
        ax.set_xticks(range(5))
        ax.set_yticks(range(5))
        ax.set_xticklabels(['0', '7.5', '15', '22.5', '30'], fontsize=11.5)
        ax.set_yticklabels(['0', '7.5', '15', '22.5', '30'], fontsize=11.5)
        ax.tick_params(length=0)
        for s in ax.spines.values():
            s.set_visible(False)
        ax.set_xlabel('strength of signal B, %', fontsize=12.5)
        ax.set_title(f'instance {k[1:]}', fontsize=15, pad=8)
    axs[0].set_ylabel('strength of signal A, %', fontsize=12.5)
    handles = [plt.Rectangle((0, 0), 1, 1, facecolor=AMBER, label='v toward -1: action A'),
               plt.Rectangle((0, 0), 1, 1, facecolor=PAPER, edgecolor=LINE, label='v near 0: hold'),
               plt.Rectangle((0, 0), 1, 1, facecolor=VIOLET, label='v toward +1: action B'),
               plt.Rectangle((0, 0), 1, 1, fill=False, edgecolor=INK, linewidth=1.3, label='scored cell')]
    f.legend(handles=handles, loc='upper left', bbox_to_anchor=(.052, .735), frameon=False, fontsize=12.5, ncol=4,
             handletextpad=.5, columnspacing=1.8, borderaxespad=0)
    header(f, title, sub)
    save(f, out, 'decision-map')


def draw_diff(rows, out, title, sub):
    f = plt.figure(figsize=(12.8, 8))
    ax = f.add_axes([.075, .14, .9, .52])
    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)))
    inst = sorted({r['instance'] for r in rows}, key=lambda s: int(s[1:]))
    for r in rows:
        if r['role'] == 'calibration':
            continue
        d = r['b'] - r['a']
        x = d + (inst.index(r['instance']) - (len(inst) - 1) / 2) * 0.9 + (r['a'] + r['b']) / 60 * 1.6 - 0.8
        scored = r['role'] == 'scored'
        ax.plot([x, x], [r['v_min'], r['v_max']], color=VIOLET if scored else MUTED, linewidth=1, alpha=.5, zorder=2)
        ax.plot([x], [r['v_mean']], 'o', markersize=5.5, zorder=3, markerfacecolor=VIOLET if scored else PAPER,
                markeredgecolor=VIOLET if scored else MUTED, markeredgewidth=1.2)
    ax.set_xticks([-30, -22.5, -15, -7.5, 0, 7.5, 15, 22.5, 30])
    ax.set_xlim(-34, 34)
    ax.set_ylim(-1.5, 1.5)
    ax.set_xlabel('strength of B minus strength of A, percentage points', fontsize=13)
    ax.set_ylabel('decision variable v', fontsize=13)
    ax.text(33.5, T + .04, 'above: action B', ha='right', fontsize=12, color=MUTED)
    ax.text(33.5, -T - .11, 'below: action A', ha='right', fontsize=12, color=MUTED)
    handles = [Line2D([], [], marker='o', linestyle='-', markersize=5.5, color=VIOLET, label='scored cell: mean and range of its steps'),
               Line2D([], [], marker='o', linestyle='-', markersize=5.5, markerfacecolor=PAPER, markeredgecolor=MUTED,
                      color=MUTED, label='transition zone (difference of 7.5 points), not scored')]
    f.legend(handles=handles, loc='upper left', bbox_to_anchor=(.052, .735), frameon=False, fontsize=12.5, ncol=2,
             handletextpad=.5, columnspacing=1.8, borderaxespad=0)
    header(f, title, sub)
    save(f, out, 'decision-diff')


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('csv_dir')
    ap.add_argument('--font', nargs='*', default=[])
    ap.add_argument('--title-map', default='The decision map of three fresh instances')
    ap.add_argument('--sub-map', default='')
    ap.add_argument('--title-diff', default='The decision follows the difference of the two strengths')
    ap.add_argument('--sub-diff', default='')
    a = ap.parse_args()
    fonts(a.font)
    rows = read(a.csv_dir)
    draw_map(rows, Path(a.csv_dir), a.title_map, a.sub_map)
    draw_diff(rows, Path(a.csv_dir), a.title_diff, a.sub_diff)
