"""F4 build summary: per-run table + totals from driver_runs.jsonl, shadow_runs.jsonl, shadow_claims.jsonl.
Prints markdown to stdout and writes build_summary.json. Contains no review labels (none exist in this half)."""
import json
from collections import Counter
from pathlib import Path
F4 = Path("out/exp/f4")
def rj(p): return [json.loads(l) for l in (F4 / p).read_text(encoding="utf-8").split("\n") if l.strip()] if (F4 / p).exists() else []
dr, sr, cl = rj("driver_runs.jsonl"), [r for r in rj("shadow_runs.jsonl") if not r.get("dry_run")], rj("shadow_claims.jsonl")
sidx = {(r["pass"], r["slug"]): r for r in sr}
print("| Pass | Vendor | Half | Driver exit | Step 03 verdict | Units | In scope | Accept A | Accept B | Pipeline $ | Jev $ | Wall s |")
print("|---|---|---|---|---|---|---|---|---|---|---|---|")
for d in dr:
    s = sidx.get((d["pass"], d["slug"]), {})
    print(f"| {d['pass']} | {d['slug']} | {['tune','confirm'][d['half']]} | {d['exit']} | {s.get('step03_verdict','-')} | "
          f"{s.get('units','-')} | {s.get('in_scope','-')} | {s.get('accept_A','-')} | {s.get('accept_B','-')} | "
          f"{s.get('pipeline_cost_usd','-')} | {s.get('sidecar_cost_usd','-')} | {d['wall_s']} |")
ins = [c for c in cl if c["scope"] == "in_scope"]
aA = [c for c in ins if c.get("accept_A_conservative") is True]
aB = [c for c in ins if c.get("accept_B_conservative") is True]
both = [c for c in ins if c.get("accept_A_conservative") is True and c.get("accept_B_conservative") is True]
err = [c for c in ins if c.get("accept_A_conservative") is None or c.get("accept_B_conservative") is None]
dedup = len({(c["claim"].lower(), c["source_url"]) for c in ins})
dedupB = len({(c["claim"].lower(), c["source_url"]) for c in aB})
tot = {"driver_runs": len(dr), "drafts_with_sidecar": len(sr), "vendors": len({d["slug"] for d in dr}),
       "exit_counts": dict(Counter(d["exit"] for d in dr)), "sets": dict(Counter(r["set"] for r in sr)),
       "step03_verdicts": dict(Counter(str(r.get("step03_verdict")) for r in sr)),
       "units": len(cl), "in_scope": len(ins), "accept_A": len(aA), "accept_B": len(aB), "accept_both": len(both),
       "accept_either": len(aA) + len(aB) - len(both), "claims_with_errored_repeat": len(err),
       "in_scope_dedup_text_url": dedup, "accept_B_dedup_text_url": dedupB,
       "accept_B_by_section": dict(Counter(c["section"] for c in aB)),
       "accept_B_by_arm_b_kind": dict(Counter(c["arm_b_kind"] for c in aB)),
       "in_scope_by_arm_b_kind": dict(Counter(c["arm_b_kind"] for c in ins)),
       "accept_B_by_half": dict(Counter(c["half"] for c in aB)),
       "ground_flag_in_scope": sum(1 for c in ins if c.get("ground_flag")),
       "step03_match_in_scope": sum(1 for c in ins if (c.get("step03") or {}).get("match", {}).get("any")),
       "pipeline_cost_usd_sum": round(sum(r.get("pipeline_cost_usd") or 0 for r in sr), 4),
       "jev_cost_usd_sum": round(sum(r.get("sidecar_cost_usd") or 0 for r in sr), 4),
       "jev_calls": sum(r.get("jev_calls") or 0 for r in sr), "jev_errors": sum(r.get("jev_errors") or 0 for r in sr)}
json.dump(tot, open(F4 / "build_summary.json", "w", encoding="utf-8"), indent=1)
print()
print(json.dumps(tot, indent=1))
