"""hr_sum.py OUTDIR TAG...: per boot, stock exl3_gemm launches of the logits head (engine.log guard lines + flag_truth counters) and
TTFT by phase from drive/requests.json. One JSON record per line on stdout."""
import json, re, statistics as st, sys
out = sys.argv[1]
for tag in sys.argv[2:]:
    log = open(f"{out}/{tag}/engine.log", errors="replace").read()
    served_at = log.find("phase")  # not in engine log; guard lines are split by class instead
    cells = re.findall(r"exl3 STOCK exl3_gemm launched: (\S+) (\S+) at (\d+) rows", log)
    head = sorted({(c, int(r)) for c, g, r in cells if g.startswith("5120x248320")})
    other = sorted({(c, g, int(r)) for c, g, r in cells if not g.startswith("5120x248320") and c in ("decode", "verify", "drafter")})
    rec = {"tag": tag, "head_stock_cells_logged": head, "step_stock_cells_other_linears": other}
    try:
        ft = json.load(open(f"{out}/{tag}/drive/flag_truth.prefill_long_decoder.json"))["counters"]
        for k in ("exl3_stock_gemm_other", "exl3_stock_gemm_step", "exl3_stock_gemm_step_captured", "mtp_fused_mixed_step", "exl3_gemv_spec_class_steps"):
            rec[k] = ft[k]["fired"]
        rec["int8_refusals"] = ft["exl3_int8_prefill_gemm"]["refusals"]
        rec["spec_class_refusals"] = ft["exl3_gemv_spec_class_steps"]["refusals"]
    except Exception as e:  # noqa: BLE001
        rec["flag_truth_error"] = repr(e)[:120]
    try:
        rows = json.load(open(f"{out}/{tag}/drive/requests.json"))
        rec["errors"] = sum(1 for r in rows if r["err"] or r["ttft_s"] is None)
        for ph in ("c1", "c4", "prefill_short"):
            t = [r["ttft_s"] for r in rows if r["phase"] == ph and r["ttft_s"] is not None]
            if t: rec[f"ttft_ms_{ph}"] = {"n": len(t), "median": round(st.median(t) * 1e3, 1), "min": round(min(t) * 1e3, 1), "mean": round(st.mean(t) * 1e3, 1)}
        for r in rows:
            if r["phase"].startswith("prefill_long"): rec[f"ttft_s_{r['tag']}"] = r["ttft_s"]; rec[f"ptok_{r['tag']}"] = r["prompt_tokens"]
    except Exception as e:  # noqa: BLE001
        rec["requests_error"] = repr(e)[:120]
    print(json.dumps(rec))
