# rcpt_diff.py DIR_A DIR_B: route/split receipt decisions of two boots, by geometry tag; prints changed picks with the
# medians of the A-pick and B-pick in each boot, and each side's clock summary when recorded.
import json, pathlib, statistics, sys
def load(d):
    out = {}
    for p in pathlib.Path(d).rglob("*.json"):
        try: e = json.loads(p.read_text())
        except Exception: continue
        if "geometry" not in e: continue
        g = e["geometry"]; dec = e.get("decision") or {}
        rows = dec.get("rows") if isinstance(dec.get("rows"), dict) else None
        pick = rows if rows is not None else {"arm": dec.get("arm")}
        t = {m: {a: statistics.median(v) for a, v in arms.items() if v} for m, arms in e.get("times", {}).items()}
        key = g.split("-i8")[0] if g.startswith(("cell", "group")) else g.rsplit("-s", 1)[0]
        out.setdefault(key, []).append((g, pick, t, e.get("clocks")))
    return out
A, B = load(sys.argv[1]), load(sys.argv[2])
same = diff = 0
for k in sorted(set(A) | set(B)):
    a, b = A.get(k), B.get(k)
    if not a or not b: print(f"ONLY {'A' if a else 'B'}: {k}"); continue
    pa, pb = a[0][1], b[0][1]
    if pa == pb: same += 1; continue
    diff += 1
    print(f"MOVED {k}:")
    if "arm" in pa:
        ta, tb = a[0][2], b[0][2]
        print(f"   A {a[0][0]} arm {pa['arm']}  B {b[0][0]} arm {pb['arm']}")
        for m in sorted(set(ta) | set(tb), key=int): print(f"   rows {m}: A {ta.get(m)}  B {tb.get(m)}")
    else:
        for m in sorted(set(pa) | set(pb), key=int):
            if pa.get(m) != pb.get(m):
                ta, tb = a[0][2].get(str(m), {}), b[0][2].get(str(m), {})
                pick = lambda t, x: round(t[x], 2) if x in t else None
                print(f"   M={m}: A {pa.get(m)} ({pick(ta, pa.get(m))} vs {pick(ta, pb.get(m))})  B {pb.get(m)} ({pick(tb, pb.get(m))} vs {pick(tb, pa.get(m))})")
    if b[0][3]: print(f"   B clocks: {json.dumps(b[0][3])[:200]}")
print(f"same {same}, moved {diff}")
