#!/usr/bin/env python3
"""Build the blind adjudication inputs for the WS1 packet (plan section F.2). Orchestrator only, run once.

Reads out/exp/ws1/adjudication_packet.jsonl (110 claims, shuffled by WS1 with seed 20260921) and writes, under
out/exp/adj/inputs/: slice_a1..a3.jsonl (the packet split in file order, 37/37/36), slice_a4.jsonl (a 30-claim
reliability overlap: the 30 packet ids with the smallest sha256("adj-overlap-2026-09-21" + id), in that order),
pages/<packet_id>.txt (a copy of each saved source page), rubrics/<cohort>.md and bundle_evidence/<slug>.md (copies
of the frozen bundle files step 03 reads), and MANIFEST.json (sha256 of every input). Nothing from Jev, step 03,
WS1's analysis or the adjudication key is copied, so the adjudicators are blind by construction.
"""
import hashlib
import json
import shutil
from pathlib import Path

ADJ = Path(__file__).resolve().parent
EXP = ADJ.parent
WS1 = EXP / "ws1"
RUNS = WS1 / "onboarding-io" / "runs"
IN = ADJ / "inputs"
SEED = "adj-overlap-2026-09-21"


def sha(p):
    return hashlib.sha256(p.read_bytes()).hexdigest()


def main():
    rows = [json.loads(x) for x in (WS1 / "adjudication_packet.jsonl").read_text(encoding="utf-8").split("\n") if x.strip()]
    assert len(rows) == 110 and len({r["packet_id"] for r in rows}) == 110
    if IN.exists():
        raise SystemExit("inputs/ already exists; refusing to rebuild (inputs are frozen once built)")
    for d in ("pages", "rubrics", "bundle_evidence"):
        (IN / d).mkdir(parents=True)
    slug_of, cohort_of = {}, {}
    for run in RUNS.iterdir():
        meta = json.loads((run / "bundle" / "meta.json").read_text(encoding="utf-8"))
        slug_of[meta.get("name") or run.name] = run.name
        cohort_of[run.name] = meta["cohort_id"]
    out = []
    for r in rows:
        slug = slug_of.get(r["vendor"]) or next(s for s in cohort_of if s == r["vendor"].lower())
        cohort = cohort_of[slug]
        page = Path(r["saved_page_path"])
        shutil.copyfile(page, IN / "pages" / f"{r['packet_id']}.txt")
        rub = IN / "rubrics" / f"{cohort}.md"
        if not rub.exists():
            shutil.copyfile(RUNS / slug / "bundle" / "rubric.md", rub)
        ev = IN / "bundle_evidence" / f"{slug}.md"
        if not ev.exists():
            shutil.copyfile(RUNS / slug / "bundle" / "evidence.md", ev)
        out.append({"packet_id": r["packet_id"], "vendor": r["vendor"], "cohort": cohort, "section": r["section"],
                    "claim": r["claim"], "source_url": r["source_url"], "as_of": r["as_of"],
                    "evidence_window": r["evidence"], "page_file": f"pages/{r['packet_id']}.txt",
                    "rubric_file": f"rubrics/{cohort}.md", "bundle_evidence_file": f"bundle_evidence/{slug}.md"})
    slices = {"a1": out[0:37], "a2": out[37:74], "a3": out[74:110]}
    slices["a4"] = sorted(out, key=lambda x: hashlib.sha256((SEED + x["packet_id"]).encode()).hexdigest())[:30]
    for k, v in slices.items():
        (IN / f"slice_{k}.jsonl").write_text("".join(json.dumps(x, ensure_ascii=False) + "\n" for x in v), encoding="utf-8")
    man = {"built_from": {"adjudication_packet.jsonl": sha(WS1 / "adjudication_packet.jsonl")}, "overlap_seed": SEED,
           "slices": {k: [x["packet_id"] for x in v] for k, v in slices.items()},
           "files": {str(p.relative_to(IN)).replace("\\", "/"): sha(p) for p in sorted(IN.rglob("*")) if p.is_file()}}
    (IN / "MANIFEST.json").write_text(json.dumps(man, indent=1), encoding="utf-8")
    print({k: len(v) for k, v in slices.items()}, "overlap from", {k: sum(1 for x in slices["a4"] if x in v) for k, v in slices.items() if k != "a4"})


if __name__ == "__main__":
    main()
