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

Adapted from out/exp/adj/build_inputs.py (F.2). Reads out/exp/f4/adjudication_packet.jsonl (148 claims, shuffled
blind by the F4 build) and writes, under out/exp/f4/adj/inputs/: slice_b1..b4.jsonl (the packet split in file order,
37 each), slice_b5.jsonl (a 30-claim reliability overlap: the 30 packet ids with the smallest
sha256("f4-overlap-2026-09-22" + id), in that order), pages/<packet_id>.txt, rubrics/<cohort>.md,
bundle_evidence/<slug>.md and MANIFEST.json. Nothing from Jev, step 03, the F4 sidecar or adjudication_key.json is
copied, so the adjudicators are blind by construction.
"""
import hashlib
import json
import shutil
from pathlib import Path

ADJ = Path(__file__).resolve().parent
F4 = ADJ.parent
RUNS = F4 / "onboarding-io-p1" / "runs"
IN = ADJ / "inputs"
SEED = "f4-overlap-2026-09-22"
N = 148


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


def main():
    rows = [json.loads(x) for x in (F4 / "adjudication_packet.jsonl").read_text(encoding="utf-8").split("\n") if x.strip()]
    assert len(rows) == N and len({r["packet_id"] for r in rows}) == N
    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_p = run / "bundle" / "meta.json"
        if not meta_p.exists():
            continue
        meta = json.loads(meta_p.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"])
        assert RUNS / slug in page.parents, (r["packet_id"], page)
        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 = {"b1": out[0:37], "b2": out[37:74], "b3": out[74:111], "b4": out[111:148]}
    slices["b5"] = 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(F4 / "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["b5"] if x in v) for k, v in slices.items() if k != "b5"})


if __name__ == "__main__":
    main()
