"""Figure 1 of journal note 23: memory of the plaids pilot's intact run on the laptop, drawn only from retained records.

  python3 draw_g4_memory.py [--font FILE ...]          (1920 x 1200 PNG, and SVG, written beside this script)

Reads, from the folder above this script:
  g4.mem.csv        the memory curve, thinned from the memory cap's log (README says how)
  g4.mem.json       the run's summary: peak from the 2 s samples, cap, elapsed time
  g4-verdict.json   the pass gate of 3.515 GiB, and the peak as the verdict states it

--font takes Latin Modern Roman font files (.ttf or .otf, or .woff if fontTools is installed), as in the earlier notes'
plotting code. Without them the figure falls back to STIXGeneral. The script stops if the files disagree with each other.
It imports nothing but the standard library and matplotlib.
"""
import argparse, csv, json, re, sys, tempfile
from pathlib import Path

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

PAPER, INK, MUTED, LINE = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf'
VIOLET = '#5924d6'
# The pilot's intact run on the server: unit memory peak, from the run table of plaids-022/README.md. Not a laptop value.
SERVER_PEAK_GIB = 5.26
FOOT = ('Model: 2 mm reduction of LSV1M (Antolík et al. 2024, CC BY 4.0), simulated with Mozaik and NEST. '
        'Simulation only, one network instance: not a biological measurement.')


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-note-23', 'axes.edgecolor': LINE, 'axes.linewidth': 1,
                         'xtick.color': MUTED, 'ytick.color': MUTED, 'axes.labelcolor': MUTED})


def load(base):
    with open(base / 'g4.mem.csv', newline='') as fh:
        rows = list(csv.DictReader(fh))
    t = [float(r['elapsed_s']) / 3600 for r in rows]
    y = [float(r['footprint_gib']) for r in rows]
    mem = json.loads((base / 'g4.mem.json').read_text())
    verdict = json.loads((base / 'g4-verdict.json').read_text())
    key = next(k for k in verdict['checks'] if k.startswith('2 peak at most'))
    gate = float(re.search(r'at most ([0-9.]+) GiB', key).group(1))
    peak, peak_h = mem['peak_footprint_gib'], mem['peak_footprint_at_s'] / 3600
    stated = re.match(r'([0-9.]+) GiB at ([0-9.]+) h', verdict['checks'][key]['detail'])
    if float(stated.group(1)) != peak or f'{peak_h:.2f}' != stated.group(2):
        sys.exit('refused: g4.mem.json and g4-verdict.json state different peaks')
    if max(y) > peak or mem['exit'] != 0 or mem['reason'] != 'exited':
        sys.exit('refused: the curve and the summary disagree')
    return t, y, peak, peak_h, gate, mem['cap_gib'], mem['elapsed_s'] / 3600


def draw(here):
    t, y, peak, peak_h, gate, cap, end_h = load(here.parent)
    f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
    f.text(.055, .94, 'felisyn  /  research note 23 (the plaids pilot on a laptop)', color=VIOLET, fontsize=15)
    f.text(.055, .872, 'The full run stayed under the memory cap', fontsize=28)
    f.text(.055, .823, 'Physical footprint of the run\'s processes on the 8 GB laptop. '
                       'The dot is the peak from the 2 s samples; the line is the log, thinned.',
           color=MUTED, fontsize=14)
    f.text(.055, .014, FOOT, fontsize=11, color=MUTED)
    ax = f.add_axes([.075, .115, .875, .675], facecolor=PAPER)
    for side in ('top', 'right', 'left'):
        ax.spines[side].set_visible(False)
    ax.set_xlim(0, 2.04)
    ax.set_ylim(0, 5.6)
    ax.set_xticks([0, .5, 1, 1.5, 2])
    ax.set_yticks(range(6))
    ax.tick_params(length=0, labelsize=13, pad=7)
    ax.grid(axis='y', color=LINE, lw=.7, zorder=0)
    ax.set_xlabel('Hours since the run started', fontsize=14, labelpad=9)
    ax.set_ylabel('Physical footprint (GiB)', fontsize=14, labelpad=9)
    ax.axhline(SERVER_PEAK_GIB, color=MUTED, lw=1.4, zorder=1)
    ax.axhline(cap, color=INK, lw=1.4, ls=(0, (6, 4)), zorder=1)
    ax.axhline(gate, color=INK, lw=1, ls=(0, (1.5, 3)), zorder=1)
    ax.plot(t, y, color=VIOLET, lw=2, solid_joinstyle='round', zorder=3)
    ax.scatter([peak_h], [peak], s=95, color=VIOLET, edgecolor=PAPER, linewidth=2, zorder=4)
    kw = dict(fontsize=14, ha='left')
    ax.text(.03, SERVER_PEAK_GIB + .09, f'Server pilot: peak {SERVER_PEAK_GIB} GiB (Linux service peak, a different meter)', va='bottom', **kw)
    ax.text(.03, cap + .08, f'Cap {cap} GiB: the run is stopped above this', va='bottom', **kw)
    ax.text(.03, gate - .09, f'Gate {gate} GiB, written before the run', va='top', **kw)
    ax.annotate(f'Laptop peak {peak:.3f} GiB, at {peak_h:.2f} h', xy=(peak_h, peak - .07), xytext=(peak_h - .02, 2.2),
                fontsize=14, ha='right', va='center', arrowprops=dict(arrowstyle='-', color=MUTED, lw=1,
                                                                      shrinkA=2, shrinkB=2,
                                                                      connectionstyle='angle,angleA=0,angleB=90'))
    ax.text(end_h - .03, .33, f'Run ends, exit 0, {end_h:.2f} h', fontsize=14, ha='right', va='center')
    f.savefig(here / 'g4-memory.png', dpi=150, facecolor=PAPER)
    f.savefig(here / 'g4-memory.svg', facecolor=PAPER, metadata={'Date': None})
    plt.close(f)


if __name__ == '__main__':
    a = argparse.ArgumentParser()
    a.add_argument('--font', nargs='*', default=[])
    p = a.parse_args()
    fonts(p.font)
    draw(Path(__file__).resolve().parent)
