"""Measured setup timeline and check outcomes for rehearsal 008, from retained receipts.

One rehearsal on the existing four-vCPU research server; no full-model simulation is depicted.
Writes figures/rehearsal-steps.png (1920 x 1200) and .svg.
"""
import csv, json
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT = Path(__file__).resolve().parent
R = ROOT / 'receipts'
steps = {row['step']: row for row in csv.DictReader((R / 'logs/steps.tsv').open(), delimiter='\t')}
runtime = json.loads((R / 'protocol-006/runtime-check.json').read_text())
compat = json.loads((R / 'protocol-006/compatibility-check.json').read_text())
regression = json.loads((R / 'regression-run/run.json').read_text())
comparison = json.loads((ROOT / 'comparison.json').read_text())
unittest_tail = (R / 'logs/protocol-unittest.log').read_text().strip().splitlines()
tests_ran = next(int(l.split()[1]) for l in unittest_tail if l.startswith('Ran '))
assert unittest_tail[-1] == 'OK'
assert comparison['python_packages']['identical'] and not comparison['python_packages']['differences']
source_files = sum(len(c['files']) for c in runtime['checks'] if 'files' in c)

groups = [
    ('Install system packages', ['bootstrap-host']),
    ('Build Python 3.9.20', ['build-python']),
    ('Fetch five pinned sources', ['fetch-sources']),
    ('Build NEST 3.4 and Python packages', ['build-runtime']),
    ('Small-model regression and plots', ['regression', 'inspect-regression', 'plot-regression', 'capture-environment']),
    ('Protocol and launch-path checks', ['install-protocol', 'protocol-unittest', 'protocol-runtime', 'protocol-compatibility',
                                         'full-runs-dir', 'protocol-preflight', 'execute-identity-checks', 'cpu-topology',
                                         'mpi-16-ranks-on-4-cores', 'mpi-4-rank-smoke']),
]
covered = {s for _, names in groups for s in names} | {'userland-before', 'copy-locks', 'install-harness'}
assert covered == set(steps), sorted(set(steps) - covered)
seconds = [sum(int(steps[s]['seconds']) for s in names) for _, names in groups]
total = sum(int(r['seconds']) for r in steps.values())
for name, row in steps.items():
    assert row['exit_code'] == row['expected'] or (row['expected'] == 'nonzero' and row['exit_code'] != '0'), name

def label(s):
    return f'{s} s' if s < 60 else f'{s // 60} min {s % 60:02d} s'

PAPER, INK, VIOLET, MUTED, LINE = '#fcfaf7', '#28222d', '#6240ab', '#776e7d', '#d8cfdf'
plt.rcParams.update({'font.family': 'STIXGeneral', 'text.color': INK, 'font.size': 14, 'svg.fonttype': 'none',
                     'axes.edgecolor': LINE, 'xtick.color': MUTED, 'ytick.color': INK})
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
f.text(.065, .94, 'felisyn  /  research note 12', color=VIOLET, fontsize=15)
f.text(.065, .869, 'Rebuilding the simulation stack in a clean environment', fontsize=29)
f.text(.065, .817, 'One rehearsal: official Ubuntu 24.04 cloud userland on the existing four-vCPU research server.',
       color=MUTED, fontsize=15)

ax = f.add_axes([.31, .29, .30, .42], facecolor=PAPER)
y = list(range(len(groups)))[::-1]
ax.barh(y, seconds, color=VIOLET, height=.56)
ax.set_yticks(y, [g for g, _ in groups], fontsize=13)
for yi, s in zip(y, seconds):
    ax.text(s + 18, yi, label(s), va='center', fontsize=13, color=INK)
ax.set_xlim(0, 1100)
ax.set_xlabel('Measured wall-clock time (seconds), one run', fontsize=13, color=MUTED)
for side in ['top', 'right']:
    ax.spines[side].set_visible(False)
ax.tick_params(axis='y', length=0)
f.text(.065, .748, 'Setup steps', fontsize=19, color=VIOLET)

x0 = .69
f.text(x0, .748, 'Outcomes', fontsize=19, color=VIOLET)
rows = [
    (f"{regression['observed_cases']} / {regression['expected_cases']}", 'upstream exact regression comparisons'),
    (f"{sum(c['pass'] for c in runtime['checks'])} / {len(runtime['checks'])}", f'runtime checks, incl. {source_files} source files'),
    (f"{compat['passed']} / {compat['total']}", 'parameter-schema checks'),
    (f"{tests_ran} / {tests_ran}", 'contract and metric unit tests'),
    (f"{comparison['python_packages']['rehearsal_count']} / {comparison['python_packages']['original_count']}",
     'pinned Python versions equal to the original build'),
    ('refused', 'hardware preflight on this host, as intended'),
    ('refused', '16 MPI ranks on 4 cores, as expected'),
]
for i, (value, text) in enumerate(rows):
    yy = .69 - i * .064
    f.text(x0, yy, value, fontsize=19, color=INK)
    f.text(x0, yy - .026, text, fontsize=12.5, color=MUTED)

line = f.add_axes([0, 0, 1, 1]); line.set(xlim=(0, 1), ylim=(0, 1)); line.axis('off')
line.plot([.065, .935], [.796, .796], color=LINE, lw=1)
line.plot([.065, .935], [.205, .205], color=LINE, lw=1)
f.text(.065, .155, f'Total {label(total)}. Example regression data byte-identical to the original run (7 October, UTC).', fontsize=17)
f.text(.065, .108, 'Same virtual machine, kernel and CPU as the original build; only the userland was new. Build scripts use four parallel jobs.',
       fontsize=13, color=MUTED)
f.text(.065, .072, 'No full-model simulation was run. This checks installation and software regression, not biological validity.',
       fontsize=13, color=MUTED)
(ROOT / 'figures').mkdir(exist_ok=True)
for ext in ['png', 'svg']:
    f.savefig(ROOT / f'figures/rehearsal-steps.{ext}', facecolor=PAPER)
print(json.dumps({'total_seconds': total, 'groups': dict(zip([g for g, _ in groups], seconds))}))
