"""Replay stored boot-race receipts through the route decision with and without the `up` arm.

usage: replay_no_up.py MAIN_DECIDE_PY MAIN_LEGS_PY BRANCH_DECIDE_PY BRANCH_LEGS_PY RECEIPT_ROOT OUT_JSONL

Three decisions per receipt (a cell or a group of one boot, every raced row):
  stored   the receipt's own `decision.rows` (what that boot served)
  main     main's `gemv_route_decide.decide` over the receipt's chains
  branch   the branch's `decide` (no `up` arm) over the same chains with the
           `up` chains dropped, which is what a boot of the branch times
Seeds are each row's stored `incumbent` (the arm decide_row held); a row seeded
`up` would be re-seeded with the fallback and is counted in `up_seed_rows`.
The decide modules import one constant from gemv_legs; it is read from the
source so the replay runs without torch.
"""

import ast
import glob
import importlib.util
import json
import os
import re
import statistics
import sys
import types

main_decide, main_legs, br_decide, br_legs, root, out_path = sys.argv[1:7]
UP = "up"


def load(decide_py, legs_py, tag):
    band = None
    for node in ast.parse(open(legs_py).read()).body:
        if isinstance(node, ast.AnnAssign) and getattr(node.target, "id", "") == "EXL3_MMA_ROUTE_BAND":
            band = eval(compile(ast.Expression(node.value), "band", "eval"))
    assert band
    for name in ("arbi_serve", "arbi_serve.weight_quant", "arbi_serve.weight_quant.exl3"):
        sys.modules[name] = types.ModuleType(name)
    stub = types.ModuleType("arbi_serve.weight_quant.exl3.gemv_legs")
    stub.EXL3_MMA_ROUTE_BAND = band
    sys.modules[stub.__name__] = stub
    name = "arbi_serve.weight_quant.exl3.gemv_route_decide"
    spec = importlib.util.spec_from_file_location(name, decide_py)
    mod = importlib.util.module_from_spec(spec)
    sys.modules[name] = mod
    spec.loader.exec_module(mod)
    del sys.modules[name]
    return mod


M = load(main_decide, main_legs, "main")
B = load(br_decide, br_legs, "branch")
assert hasattr(M, "ARM_UP") and not hasattr(B, "ARM_UP")

n = dict(receipts=0, rows=0, raced_rows=0, up_timed_rows=0, up_fastest_median_rows=0, up_pick_rows=0,
         up_seed_rows=0, changed_rows=0, stored_vs_main_rows=0)
with open(out_path, "w") as out:
    for f in sorted(glob.glob(os.path.join(root, "**", "*.json"), recursive=True)):
        base = os.path.basename(f)
        if not base.startswith(("cell-", "group-")):
            continue
        d = json.load(open(f))
        if "times" not in d or "decision" not in d:
            continue
        group = base.startswith("group-")
        times = {int(m): {a: list(t) for a, t in arms.items()} for m, arms in d["times"].items()}
        per = {int(m): r for m, r in d["decision"]["per_row"].items()}
        stored = {int(m): a for m, a in d["decision"]["rows"].items()}
        seeds = {m: r["incumbent"] for m, r in per.items()}
        key = None
        if not group:
            key = tuple(int(v) for v in re.match(r"cell-(\d+)-(\d+)-(\d+)x(\d+)", base).groups())
        nur_m = frozenset() if group else M.EXL3_NO_UPSTREAM_CELL_ROWS.get(key, frozenset())
        nur_b = frozenset() if group else B.EXL3_NO_UPSTREAM_CELL_ROWS.get(key, frozenset())
        on_main, _ = M.decide(times, seeds, group=group, no_upstream_rows=nur_m)
        fb = "members" if group else "served"
        t2 = {m: {a: t for a, t in arms.items() if a != UP} for m, arms in times.items()}
        s2 = {m: (fb if a == UP else a) for m, a in seeds.items()}
        on_branch, _ = B.decide(t2, s2, group=group, no_upstream_rows=nur_b)
        up_timed = sorted(m for m, arms in times.items() if arms.get(UP))
        med = {m: {a: statistics.median(t) for a, t in arms.items() if t} for m, arms in times.items()}
        up_fastest = [m for m in up_timed if min(med[m], key=med[m].get) == UP]
        up_pick = sorted({m for m, a in stored.items() if a == UP} | {m for m, a in on_main.items() if a == UP})
        up_seed = sorted(m for m, a in seeds.items() if a == UP)
        changed = {m: [on_main[m], on_branch.get(m)] for m in on_main if on_main[m] != on_branch.get(m)}
        mism = {m: [stored.get(m), on_main[m]] for m in on_main if stored.get(m) != on_main[m]}
        ki = d.get("key_inputs", {})
        rel = os.path.relpath(f, root)
        r = dict(receipt=rel, boot=rel.split(os.sep)[1] if rel.split(os.sep)[0] in ("201", "rk81", "rk82") else rel.split(os.sep)[0],
                 card=ki.get("device_name"), sms=ki.get("device_sms"), race_version=ki.get("version"),
                 up_armed=ki.get("arming", {}).get("up_armed"), geometry=d.get("geometry"),
                 raced_rows=sorted(times), rows=len(on_main), up_timed_rows=up_timed,
                 up_fastest_median_rows=up_fastest, up_pick_rows=up_pick, up_seed_rows=up_seed,
                 main_vs_branch={str(k): v for k, v in changed.items()},
                 stored_vs_main={str(k): v for k, v in mism.items()})
        if up_fastest:
            # how far ahead upstream's GEMV was where its median led, and what served instead
            r["up_fastest_detail"] = {
                str(m): dict(up_us=round(med[m][UP], 3), pick=on_main[m], pick_us=round(med[m].get(on_main[m], float("nan")), 3),
                             up_lead_pct=round(100.0 * (med[m].get(on_main[m], float("nan")) / med[m][UP] - 1.0), 2))
                for m in up_fastest
            }
        out.write(json.dumps(r, sort_keys=True) + "\n")
        n["receipts"] += 1
        n["rows"] += len(on_main)
        n["raced_rows"] += len(times)
        n["up_timed_rows"] += len(up_timed)
        n["up_fastest_median_rows"] += len(up_fastest)
        n["up_pick_rows"] += len(up_pick)
        n["up_seed_rows"] += len(up_seed)
        n["changed_rows"] += len(changed)
        n["stored_vs_main_rows"] += len(mism)
    out.write(json.dumps(dict(summary=n), sort_keys=True) + "\n")
print(json.dumps(n))
