# served_cost.py DIR_A DIR_B: per route geometry and row, the median time of the arm each boot DECIDED to serve; prints
# rows where the served time moved > 3%, and per-cell sums over the rows both boots decided. Tags matched with the -p<pin> part dropped.
import json, pathlib, re, 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 or not str(e["geometry"]).startswith(("cell", "group")): continue
        dec = (e.get("decision") or {}).get("rows")
        if not isinstance(dec, dict): continue
        key = re.sub(r"-p[A-Za-z0-9_]+", "", e["geometry"].split("-i8")[0])
        t = {int(m): {a: statistics.median(v) for a, v in arms.items() if v} for m, arms in e.get("times", {}).items()}
        out[key] = {int(m): (a, t.get(int(m), {}).get(a)) for m, a in dec.items()}
    return out
A, B = load(sys.argv[1]), load(sys.argv[2])
tot_a = tot_b = 0.0
for k in sorted(set(A) & set(B)):
    sa = sb = 0.0
    for m in sorted(set(A[k]) & set(B[k])):
        (aa, ta), (ab, tb) = A[k][m], B[k][m]
        if ta is None or tb is None: continue
        sa += ta; sb += tb
        if abs(tb - ta) > 0.03 * ta: print(f"  {k} M={m}: A {aa} {ta:.1f}  B {ab} {tb:.1f}  ({100*(tb/ta-1):+.1f}%)")
    if sa: print(f"{k}: sum A {sa:.1f} B {sb:.1f} ({100*(sb/sa-1):+.2f}%)")
    tot_a += sa; tot_b += sb
print(f"TOTAL over decided rows: A {tot_a:.1f} B {tot_b:.1f} ({100*(tot_b/tot_a-1):+.2f}%)")
