"""Reproduce the reported per-schedule recovery outcomes from the public observations.

Usage: python3 recovery-outcomes.py training-recovery-observations-recovered.json
Writes CSV to stdout. Standard library only.
"""
import argparse
import csv
import hashlib
import json
import sys
from pathlib import Path

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("observations", type=Path)
args = parser.parse_args()
raw = args.observations.read_bytes()
if hashlib.sha256(raw).hexdigest() != "7877bcb0c40a1f05c21ee855efc2d874e2e859844509a4d0f71f8962654e6790":
    parser.error("Expected the published training recovery observations")
source = json.loads(raw)["cohorts"]["notice_cadence_302m_one_a10"]
reference = {row["step"]: row["loss_hex"] for row in source["runs"]["REF-s0"]["steps"]}

def measure(key):
    run = source["runs"][key]
    start, = [e["t0"] for e in run["events"] if e["kind"] == "t0"]
    schedule, = [e["schedule"] for e in run["events"] if e["kind"] == "run"]
    horizon = start + 1500
    rows = sorted((r["wall"], r["step"]) for r in run["steps"] if r["wall"] <= horizon)
    assert all(reference[r["step"]] == r["loss_hex"] for r in run["steps"])
    timeline = [(wall, 1, step) for wall, step in rows]
    by_reason = {"notice": 0, "reclaim": 0, "unannounced": 0}
    for event in run["events"]:
        if event["kind"] != "attempt" or event["att"] == 1 or event["wall"] > horizon:
            continue
        before = max(row for row in rows if row[0] < event["wall"])[1]
        after = min(row for row in rows if row[0] > event["wall"])[1]
        resumed = event["resume_step"]
        assert before >= resumed and after == resumed + 1
        by_reason[event["why"]] += before - resumed
        timeline.append((event["wall"], 0, resumed))
    timeline.sort()
    unique = {step for _,step in rows}
    final = timeline[-1][2]
    assert unique == set(range(1, max(unique)+1))
    repeated = len(rows)-len(unique)
    unrecovered = max(unique)-final
    assert sum(by_reason.values()) == repeated + unrecovered
    assert final == source["recorded_summary"]["runs"][key]["progress"]
    return schedule, start, timeline, final, repeated, unrecovered, by_reason

writer = csv.writer(sys.stdout, lineterminator="\n")
writer.writerow(["schedule","policy","retained_updates","repeated_updates","unrecovered_updates","warned_rollback","unexpected_rollback",
                 "file_policy_final_step","seconds_to_same_durable_step"])
policies = {"A":"files", "B":"files_plus_notice_snapshots",
            "C":"files_131s_plus_notice_snapshots", "D":"notice_snapshots_only"}
for seed in (1, 2, 3):
    runs = {arm:measure(f"{arm}-s{seed}") for arm in policies}
    target = runs["A"][3]
    for arm, (schedule, start, timeline, final, repeated, unrecovered, losses) in runs.items():
        assert schedule == runs["A"][0]
        seconds = None
        if final >= target:
            last_below = max(i for i,row in enumerate(timeline) if row[2] < target)
            crossing = timeline[last_below+1]
            assert crossing[1:] == (1, target)
            seconds = round(crossing[0]-start,6)
        writer.writerow([seed,policies[arm],final,repeated,unrecovered,losses["reclaim"]+losses["notice"],
                         losses["unannounced"],target,seconds])
