"""Condense base-vs-branch race chains into one JSON record per (card, pack, cell, M): each tree's best in-house
median and chain spread, the int8 arm's medians, the best upstream arm, and the verdict the receipt reads
(slower/faster beyond both trees' chain spread, upstream ahead by >2%)."""
import glob, json, statistics as st, sys
OURS = ("mma", "mma_p1", "mma_p3", "mma_pre", "simt", "i8", "mma_group", "simt_group", "members_mma")
UP = ("served", "auto", "up_gemv", "members_served", "members_up_gemv")
def load(pat):
    acc = {}
    for f in sorted(glob.glob(pat)):
        for r in json.load(open(f)):
            name = f'{r["in_f"]}x{r["out_f"]}' if r["kind"] == "cell" else f'{r["in_f"]}x' + "+".join(map(str, r["widths"]))
            acc.setdefault((name, r["M"]), []).append(r["us"])
    return acc
card, pack, base_pat, br_pat = sys.argv[1:5]
A, B = load(base_pat), load(br_pat)
best = lambda ch, arms: [min((v for a, v in u.items() if a in arms), default=float("nan")) for u in ch]
sp = lambda v: (max(v) - min(v)) / st.median(v) * 100
for k in sorted(set(A) & set(B)):
    oa, ob, ua = best(A[k], OURS), best(B[k], OURS), best(A[k] + B[k], UP)
    d = st.median(ob) / st.median(oa) * 100 - 100
    noise = max(sp(oa), sp(ob))
    ia = [u["i8"] for u in A[k] if "i8" in u]; ib = [u["i8"] for u in B[k] if "i8" in u]
    print(json.dumps({"card": card, "pack": pack, "cell": k[0], "M": k[1], "base_us": round(st.median(oa), 2), "branch_us": round(st.median(ob), 2),
                      "delta_pct": round(d, 2), "spread_pct": round(noise, 2), "i8_base": round(st.median(ia), 2) if ia else None,
                      "i8_branch": round(st.median(ib), 2) if ib else None, "upstream_us": round(st.median(ua), 2),
                      "verdict": "slower" if d > noise and d > 0.5 else "faster" if -d > noise and d < -0.5 else "same",
                      "upstream_ahead": st.median(ua) < st.median(ob) * 0.98}))
