#!/usr/bin/env python3
"""Build frozen post-cutoff corpora (Corpus-2026, Arm 3A superforecasters,
Arm 3B 2026 Manifold comments, verbatim & [PROB]-redacted) and Arm 2
pre-cutoff 2x2 length-matched arguments using Qwen2.5-1.5B-Instruct."""
import datetime
import gc
import hashlib
import json
import random
import re
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "code"))
import text_baseline  # noqa: E402

DATA_RAW = ROOT / "data" / "raw"
DATA_DIR = ROOT / "data"
OUT_DIR = ROOT / "out"
OUT_DIR.mkdir(parents=True, exist_ok=True)

GEN_MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
GEN_REV = "989aa7980e4cf806f80c7fef2b1adb7bc71aa306"
SEED = 20261123


def clean_ws(s: str) -> str:
    return re.sub(r"\s+", " ", s or "").strip()


def extract_tiptap(node) -> str:
    if isinstance(node, str):
        return node
    if isinstance(node, dict):
        parts = []
        if isinstance(node.get("text"), str):
            parts.append(node["text"])
        for ch in node.get("content", []):
            t = extract_tiptap(ch)
            if t:
                parts.append(t)
        return " ".join(parts)
    if isinstance(node, list):
        return " ".join(extract_tiptap(x) for x in node)
    return ""


def parse_iso_ms(s: str):
    if not s:
        return None
    dt = datetime.datetime.fromisoformat(s.replace("Z", "+00:00"))
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=datetime.timezone.utc)
    return int(dt.timestamp() * 1000)


def redact_probs(text: str) -> str:
    """Mask explicit probability/percentage/odds expressions while preserving years/dates."""
    s = text
    # Percentages and ranges like 50-60%, ~30%, 12.5 %, 75 percent
    s = re.sub(r"~?\b\d{1,3}(?:\.\d+)?(?:\s*[-–to]+\s*\d{1,3}(?:\.\d+)?)?\s*%", "[PROB]", s)
    s = re.sub(r"\b\d{1,3}(?:\.\d+)?\s*(?:percent|pct)\b", "[PROB]", s, flags=re.I)
    # Decimal probabilities 0.xx or .xx (avoid version numbers like 1.5.2)
    s = re.sub(r"(?<![\d.])0\.\d{1,4}(?!\.\d)\b", "[PROB]", s)
    # Explicit odds / ratios like "3:1 odds" or "1 in 5 chance"
    s = re.sub(r"\b\d+\s*:\s*\d+\b", "[PROB]", s)
    s = re.sub(r"\b\d+\s+(?:in|out of)\s+\d+\s+(?:chance|odds|probability)?\b", "[PROB]", s, flags=re.I)
    s = re.sub(r"(?:\[PROB\]\s*){2,}", "[PROB] ", s)
    return clean_ws(s)


def trunc_words(s: str, max_chars: int = 1000) -> str:
    s = clean_ws(s)
    if len(s) <= max_chars:
        return s
    cut = s[:max_chars].rsplit(" ", 1)[0]
    return cut + " ..."


def sha256_file(p: Path) -> str:
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for ch in iter(lambda: f.read(1 << 20), b""):
            h.update(ch)
    return h.hexdigest()


def build_corpus_2026():
    fb = DATA_RAW / "forecastbench"
    res_map = {}
    for p in sorted((fb / "resolution_sets").glob("2026-*_resolution_set.json")):
        for row in json.loads(p.read_text()).get("resolutions", []):
            qid = row.get("id")
            if isinstance(qid, str) and row.get("resolved") is True and row.get("resolved_to") in (0, 1, 0.0, 1.0):
                rd = row.get("resolution_date") or ""
                if rd >= "2026-01-01" and (qid not in res_map or rd < res_map[qid]["resolution_date"]):
                    res_map[qid] = row

    q_earliest = {}
    for p in sorted((fb / "question_sets").glob("2026-*-llm.json")):
        if p.name[:10] > "2026-09-13":
            continue
        for q in json.loads(p.read_text()).get("questions", []):
            qid = q.get("id")
            if isinstance(qid, str) and qid not in q_earliest:
                qc = dict(q)
                qc["_round_date"] = p.name[:10]
                q_earliest[qid] = qc

    buckets = defaultdict(list)
    for qid, q in sorted(q_earliest.items()):
        src = q.get("source")
        if src not in {"manifold", "metaculus", "polymarket", "infer"} or qid not in res_map:
            continue
        try:
            pmkt = float(q.get("freeze_datetime_value"))
        except Exception:
            continue
        if not (0.10 <= pmkt <= 0.90):
            continue
        r = res_map[qid]
        y = int(round(float(r["resolved_to"])))
        buckets[(src, y)].append({
            "id": qid,
            "source": src,
            "round_date": q["_round_date"],
            "freeze_datetime": q.get("freeze_datetime"),
            "resolution_date": r["resolution_date"],
            "resolved_to": y,
            "p_mkt": pmkt,
            "question": clean_ws(q.get("question", "")),
            "resolution_criteria": trunc_words(q.get("resolution_criteria", ""), 600),
            "background": trunc_words(q.get("background", ""), 400),
        })

    rng = random.Random(SEED)
    quotas = {
        ("manifold", 1): 35, ("manifold", 0): 35,
        ("metaculus", 1): 35, ("metaculus", 0): 35,
        ("polymarket", 1): 80, ("polymarket", 0): 80,
    }
    selected = []
    for k, k_n in quotas.items():
        pool = sorted(buckets[k], key=lambda x: x["id"])
        rng.shuffle(pool)
        assert len(pool) >= k_n, f"Bucket {k} has only {len(pool)} < {k_n}"
        selected.extend(pool[:k_n])

    selected.sort(key=lambda x: x["id"])
    with open(DATA_DIR / "corpus_2026.jsonl", "w") as f:
        for row in selected:
            f.write(json.dumps(row) + "\n")
    return selected, q_earliest, res_map


def build_arm3a():
    fb = DATA_RAW / "forecastbench"
    q24 = {q["id"]: q for q in json.loads((fb / "question_sets" / "2024-07-21-human.json").read_text())["questions"]}
    r24 = json.loads((fb / "resolution_sets" / "2024-07-21_resolution_set.json").read_text())["resolutions"]
    sf24 = json.loads((fb / "forecast_sets" / "2024-07-21.ForecastBench.human_super_individual.json").read_text())["forecasts"]

    r24_map = {}
    for row in r24:
        if isinstance(row.get("id"), str) and row.get("resolved") is True and row.get("resolved_to") in (0, 1, 0.0, 1.0):
            r24_map[(row["id"], row.get("resolution_date"))] = row

    sf_by_key = defaultdict(list)
    for f in sf24:
        if isinstance(f.get("id"), str) and isinstance(f.get("reasoning"), str) and f.get("forecast") is not None:
            txt = clean_ws(f["reasoning"])
            if len(txt) >= 80:
                sf_by_key[(f["id"], f.get("resolution_date"))].append({
                    "user_id": str(f.get("user_id", "")),
                    "forecast": float(f["forecast"]),
                    "reasoning": trunc_words(txt, 1200),
                })

    by_qid = {}
    for k, flist in sf_by_key.items():
        r = r24_map.get(k)
        if r is None and k[1] is None:
            cands = sorted(
                [v for (qid, _rd), v in r24_map.items() if qid == k[0] and (v.get("resolution_date") or "") >= "2024-10-01"],
                key=lambda x: x.get("resolution_date") or "",
            )
            r = cands[0] if cands else None
        if r is None:
            continue
        rdate = r.get("resolution_date") or ""
        if rdate < "2024-10-01":
            continue
        qid = k[0]
        if qid not in by_qid or rdate < by_qid[qid]["resolution_date"]:
            qmeta = q24.get(qid, {})
            try:
                pmkt = float(qmeta.get("freeze_datetime_value"))
            except Exception:
                pmkt = None
            by_qid[qid] = {
                "id": qid,
                "source": qmeta.get("source", r.get("source", "")),
                "question": clean_ws(qmeta.get("question", "")),
                "resolution_criteria": trunc_words(qmeta.get("resolution_criteria", ""), 600),
                "resolution_date": rdate,
                "resolved_to": int(round(float(r["resolved_to"]))),
                "p_mkt": pmkt,
                "eligible_qwen25": rdate >= "2024-10-01",
                "eligible_smollm2": rdate >= "2024-12-01",
                "eligible_qwen3": rdate >= "2025-09-01",
                "rationales": flist,
            }

    questions_3a = []
    pairs_3a = []
    indiv_3a = []
    for qid in sorted(by_qid):
        item = by_qid[qid]
        if not item["question"]:
            continue
        fl = sorted(item["rationales"], key=lambda x: (x["forecast"], x["user_id"], x["reasoning"]))
        q_row = {k: v for k, v in item.items() if k != "rationales"}
        questions_3a.append(q_row)

        lo, hi = fl[0], fl[-1]
        if hi["forecast"] - lo["forecast"] >= 0.20:
            y = item["resolved_to"]
            # Accuracy: 1 - |forecast - y|; binary ordering on Y in {0,1} strictly favors hi if y==1 else lo
            acc_hi = 1.0 - abs(hi["forecast"] - y)
            acc_lo = 1.0 - abs(lo["forecast"] - y)
            more_acc = "high" if acc_hi > acc_lo else "low"
            pairs_3a.append({
                **q_row,
                "high_user_id": hi["user_id"],
                "high_forecast": hi["forecast"],
                "high_text": hi["reasoning"],
                "high_text_redacted": redact_probs(hi["reasoning"]),
                "low_user_id": lo["user_id"],
                "low_forecast": lo["forecast"],
                "low_text": lo["reasoning"],
                "low_text_redacted": redact_probs(lo["reasoning"]),
                "spread": round(hi["forecast"] - lo["forecast"], 4),
                "strict_opposing": (hi["forecast"] >= 0.55 and lo["forecast"] <= 0.45),
                "more_accurate_side": more_acc,
            })

        # Sample up to 3 distinct rationales (min, median, max)
        idxs = sorted({0, len(fl) // 2, len(fl) - 1})
        seen_txt = set()
        for idx in idxs:
            r_obj = fl[idx]
            if r_obj["reasoning"] in seen_txt:
                continue
            seen_txt.add(r_obj["reasoning"])
            indiv_3a.append({
                **q_row,
                "rationale_idx": idx,
                "user_id": r_obj["user_id"],
                "forecast": r_obj["forecast"],
                "accuracy": round(1.0 - abs(r_obj["forecast"] - item["resolved_to"]), 6),
                "text": r_obj["reasoning"],
                "text_redacted": redact_probs(r_obj["reasoning"]),
                "word_count": len(r_obj["reasoning"].split()),
            })

    with open(DATA_DIR / "arm3a_questions.jsonl", "w") as f:
        for row in questions_3a:
            f.write(json.dumps(row) + "\n")
    with open(DATA_DIR / "arm3a_pairs.jsonl", "w") as f:
        for row in pairs_3a:
            f.write(json.dumps(row) + "\n")
    with open(DATA_DIR / "arm3a_individual.jsonl", "w") as f:
        for row in indiv_3a:
            f.write(json.dumps(row) + "\n")
    return questions_3a, pairs_3a, indiv_3a


def build_arm3b(q_earliest, res_map):
    questions_3b = []
    pairs_3b = []
    indiv_3b = []
    for qid in sorted(q_earliest):
        q = q_earliest[qid]
        if q.get("source") != "manifold" or qid not in res_map:
            continue
        cp = DATA_RAW / "manifold_comments" / f"{qid}.json"
        mp = DATA_RAW / "manifold_markets" / f"{qid}.json"
        if not cp.exists() or not mp.exists():
            continue
        mk = json.loads(mp.read_text())
        res_ms = mk.get("resolutionTime")
        frz_ms = parse_iso_ms(q.get("freeze_datetime"))
        if not res_ms:
            continue
        cutoff_ms = min(frz_ms or res_ms, res_ms - 7 * 86400 * 1000)
        cs = json.loads(cp.read_text())

        pre = []
        for c in cs:
            if c.get("commentType") == "contract" and c.get("createdTime", 10**18) < cutoff_ms:
                txt = clean_ws(extract_tiptap(c.get("content", "")))
                if len(txt) >= 100:
                    pre.append({
                        "comment_id": c.get("id"),
                        "user_id": c.get("userId", ""),
                        "created_ms": c.get("createdTime"),
                        "position_outcome": c.get("commentorPositionOutcome"),
                        "position_shares": float(c.get("commentorPositionShares") or 0.0),
                        "position_prob": c.get("commentorPositionProb"),
                        "text": trunc_words(txt, 1000),
                    })
        if len(pre) < 2:
            continue

        r = res_map[qid]
        try:
            pmkt = float(q.get("freeze_datetime_value"))
        except Exception:
            pmkt = None
        q_row = {
            "id": qid,
            "source": "manifold",
            "freeze_datetime": q.get("freeze_datetime"),
            "freeze_ms": frz_ms,
            "resolution_ms": res_ms,
            "cutoff_ms": cutoff_ms,
            "resolution_date": r["resolution_date"],
            "resolved_to": int(round(float(r["resolved_to"]))),
            "p_mkt": pmkt,
            "question": clean_ws(q.get("question", "")),
            "resolution_criteria": trunc_words(q.get("resolution_criteria", ""), 600),
        }
        questions_3b.append(q_row)

        yes_c = [c for c in pre if c["position_outcome"] == "YES" and c["position_shares"] > 0]
        no_c = [c for c in pre if c["position_outcome"] == "NO" and c["position_shares"] > 0]
        if yes_c and no_c:
            best_yes = max(yes_c, key=lambda x: (x["position_shares"], len(x["text"]), x["comment_id"]))
            best_no = max(no_c, key=lambda x: (x["position_shares"], len(x["text"]), x["comment_id"]))
            pairs_3b.append({
                **q_row,
                "yes_comment_id": best_yes["comment_id"],
                "yes_shares": best_yes["position_shares"],
                "yes_created_ms": best_yes["created_ms"],
                "yes_text": best_yes["text"],
                "yes_text_redacted": redact_probs(best_yes["text"]),
                "no_comment_id": best_no["comment_id"],
                "no_shares": best_no["position_shares"],
                "no_created_ms": best_no["created_ms"],
                "no_text": best_no["text"],
                "no_text_redacted": redact_probs(best_no["text"]),
                "more_accurate_side": "YES" if q_row["resolved_to"] == 1 else "NO",
            })

        # Up to 4 longest substantive comments for individual scoring
        top_ind = sorted(pre, key=lambda x: (-len(x["text"]), x["comment_id"]))[:4]
        for idx, c in enumerate(top_ind):
            indiv_3b.append({
                **q_row,
                "comment_idx": idx,
                "comment_id": c["comment_id"],
                "created_ms": c["created_ms"],
                "position_outcome": c["position_outcome"],
                "position_shares": c["position_shares"],
                "text": c["text"],
                "text_redacted": redact_probs(c["text"]),
                "word_count": len(c["text"].split()),
            })

    with open(DATA_DIR / "arm3b_questions.jsonl", "w") as f:
        for row in questions_3b:
            f.write(json.dumps(row) + "\n")
    with open(DATA_DIR / "arm3b_pairs.jsonl", "w") as f:
        for row in pairs_3b:
            f.write(json.dumps(row) + "\n")
    with open(DATA_DIR / "arm3b_individual.jsonl", "w") as f:
        for row in indiv_3b:
            f.write(json.dumps(row) + "\n")
    return questions_3b, pairs_3b, indiv_3b


def clean_generated_arg(t: str) -> str:
    t = re.sub(r"\bSentence\s+[123]\s*:\s*", "", t)
    t = clean_ws(t)
    if t and t[-1] not in ".!?":
        idx = max(t.rfind("."), t.rfind("!"), t.rfind("?"))
        if idx >= 40:
            t = t[:idx + 1].strip()
    return t


def trim_complete_sentences(t: str, target_max: int) -> str:
    sents = re.split(r"(?<=[.!?])\s+", t)
    while len(sents) > 2 and len(" ".join(sents).split()) > target_max:
        sents = sents[:-1]
    return " ".join(sents)


def build_arm2_arguments(corpus_2026):
    cells = [("YES", "strong"), ("YES", "weak"), ("NO", "strong"), ("NO", "weak")]
    cache_path = DATA_DIR / "arm2_cache.json"
    all_cached = False
    if cache_path.exists():
        raw_cache = json.loads(cache_path.read_text())
        generated = {qid: {tuple(k.split("_")): v for k, v in cells_d.items()} for qid, cells_d in raw_cache.items()}
        all_cached = all(all((s, ql) in generated.get(q["id"], {}) for s, ql in cells) for q in corpus_2026)
    else:
        generated = {q["id"]: {} for q in corpus_2026}

    regen_count = 0
    if not all_cached:
        print("[Arm 2] Loading pre-cutoff Qwen2.5-1.5B-Instruct for argument generation...")
        tok = AutoTokenizer.from_pretrained(GEN_MODEL_ID, revision=GEN_REV, local_files_only=True)
        tok.padding_side = "left"
        if tok.pad_token_id is None:
            tok.pad_token_id = tok.eos_token_id
        dev = "mps" if torch.backends.mps.is_available() else "cpu"
        dtype = torch.float16 if dev == "mps" else torch.float32
        model = AutoModelForCausalLM.from_pretrained(GEN_MODEL_ID, revision=GEN_REV, dtype=dtype, local_files_only=True).to(dev).eval()

        def make_prompt(q, side, quality, attempt=0):
            side_word = "YES (it will happen)" if side == "YES" else "NO (it will not happen)"
            bg = f"\nBackground context: {q['background']}" if q.get("background") else ""
            strict_len = "Keep strictly between 50 and 65 words." if attempt > 0 else "Write about 55-65 words."
            if quality == "strong":
                instr = (
                    f"Write three concise sentences arguing that the answer to this forecasting question will be {side_word}: "
                    f"first cite a specific historical base rate or reference class, next explain a concrete causal mechanism driving that outcome, "
                    f"and finally identify an observable early indicator to watch. "
                    f"{strict_len} Output only the 3-sentence paragraph with no heading, numbering, or bullets."
                )
            else:
                instr = (
                    f"Write three concise sentences arguing that the answer to this forecasting question will be {side_word}. "
                    f"Rely only on vague intuition, general sentiment, and circular repetition, without mentioning any base rate, statistics, specific mechanism, or testable indicator. "
                    f"{strict_len} Output only the 3-sentence paragraph with no heading, numbering, or bullets."
                )
            content = f"Question: {q['question']}{bg}\n\n{instr}"
            return tok.apply_chat_template([{"role": "user", "content": content}], tokenize=False, add_generation_prompt=True)

        @torch.no_grad()
        def gen_batch(prompts, temp=0.0):
            order = sorted(range(len(prompts)), key=lambda idx: len(prompts[idx]))
            outs = [""] * len(prompts)
            bs = 32
            for start in range(0, len(order), bs):
                batch_idxs = order[start:start+bs]
                batch_prompts = [prompts[idx] for idx in batch_idxs]
                enc = tok(batch_prompts, return_tensors="pt", padding=True, add_special_tokens=False).to(dev)
                kw = {"max_new_tokens": 110, "pad_token_id": tok.pad_token_id}
                if temp > 0:
                    kw.update({"do_sample": True, "temperature": temp, "top_p": 0.95})
                else:
                    kw.update({"do_sample": False})
                g = model.generate(**enc, **kw)
                dec = tok.batch_decode(g[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)
                for idx, txt in zip(batch_idxs, dec):
                    t = clean_ws(txt)
                    t = re.sub(r"^(?:Argument|Response|Answer)\s*:\s*", "", t, flags=re.I)
                    outs[idx] = t
            return outs

        t0 = time.time()
        for side, qual in cells:
            if all((side, qual) in generated[q["id"]] for q in corpus_2026):
                continue
            prompts = [make_prompt(q, side, qual, 0) for q in corpus_2026]
            texts = gen_batch(prompts, temp=0.0)
            for q, txt in zip(corpus_2026, texts):
                generated[q["id"]][(side, qual)] = txt
            cache_path.write_text(json.dumps({qid: {f"{s}_{ql}": v for (s, ql), v in d.items()} for qid, d in generated.items()}))
            print(f"  Generated initial {side}/{qual} ({len(texts)} items, elapsed={time.time()-t0:.1f}s)")

        del model
        gc.collect()
        if dev == "mps":
            torch.mps.empty_cache()

    trimmed_count = 0
    rows = []
    ratios_sw, ratios_yn = [], []
    for q in corpus_2026:
        g = {k: clean_generated_arg(v) for k, v in generated[q["id"]].items()}
        min_w = max(25, min(len(v.split()) for v in g.values()))
        target_max = int(min_w * 1.25)
        for k, v in list(g.items()):
            nv = trim_complete_sentences(v, target_max)
            if nv != v:
                trimmed_count += 1
            g[k] = nv
        wc = {f"{s}_{ql}": len(g[(s, ql)].split()) for s, ql in cells}
        ratios_sw.append(wc["YES_strong"] / max(1, wc["YES_weak"]))
        ratios_sw.append(wc["NO_strong"] / max(1, wc["NO_weak"]))
        ratios_yn.append(wc["YES_strong"] / max(1, wc["NO_strong"]))
        ratios_yn.append(wc["YES_weak"] / max(1, wc["NO_weak"]))
        rows.append({
            "id": q["id"],
            "source": q["source"],
            "resolved_to": q["resolved_to"],
            "p_mkt": q["p_mkt"],
            "question": q["question"],
            "resolution_criteria": q["resolution_criteria"],
            "args": {f"{s}_{ql}": g[(s, ql)] for s, ql in cells},
            "word_counts": wc,
        })

    with open(DATA_DIR / "arm2_arguments.jsonl", "w") as f:
        for r in rows:
            f.write(json.dumps(r) + "\n")

    # Pre-scoring zero-leakage check using code/text_baseline.py
    y_arr = np.array([r["resolved_to"] for r in rows])
    leakage = {}
    for key in ["YES_strong", "YES_weak", "NO_strong", "NO_weak"]:
        txts = [r["args"][key] for r in rows]
        sc = text_baseline.cv_scores(txts, y_arr, repeats=5, folds=5, seed=0)
        leakage[key] = [round(v, 4) for v in text_baseline.auc_ci(y_arr, sc, n=1000, seed=0)]

    from sklearn.metrics import roc_auc_score
    len_auroc_sw = float(roc_auc_score(
        [1]*len(rows) + [0]*len(rows),
        [r["word_counts"]["YES_strong"] for r in rows] + [r["word_counts"]["YES_weak"] for r in rows],
    ))
    len_auroc_yn = float(roc_auc_score(
        [1]*2*len(rows) + [0]*2*len(rows),
        [r["word_counts"]["YES_strong"] for r in rows] + [r["word_counts"]["YES_weak"] for r in rows] +
        [r["word_counts"]["NO_strong"] for r in rows] + [r["word_counts"]["NO_weak"] for r in rows],
    ))

    audit = {
        "n_questions": len(rows),
        "regen_rounds_items": regen_count,
        "sentence_trimmed_cells": trimmed_count,
        "word_counts_mean": {
            k: round(float(np.mean([r["word_counts"][k] for r in rows])), 2)
            for k in ["YES_strong", "YES_weak", "NO_strong", "NO_weak"]
        },
        "length_auroc_strong_vs_weak": round(len_auroc_sw, 4),
        "length_auroc_yes_vs_no": round(len_auroc_yn, 4),
        "ratio_strong_weak_range": [round(min(ratios_sw), 3), round(max(ratios_sw), 3)],
        "ratio_yes_no_range": [round(min(ratios_yn), 3), round(max(ratios_yn), 3)],
        "leakage_tfidf_predicting_truth": leakage,
    }
    return rows, audit


def main():
    c26, q_earliest, res_map = build_corpus_2026()
    q3a, p3a, i3a = build_arm3a()
    q3b, p3b, i3b = build_arm3b(q_earliest, res_map)
    _, arm2_audit = build_arm2_arguments(c26)

    corpus_audit = {
        "corpus_2026": {
            "n": len(c26),
            "by_source": dict(Counter(r["source"] for r in c26)),
            "by_y": dict(Counter(r["resolved_to"] for r in c26)),
            "min_resolution_date": min(r["resolution_date"] for r in c26),
            "max_resolution_date": max(r["resolution_date"] for r in c26),
            "p_mkt_range": [round(min(r["p_mkt"] for r in c26), 4), round(max(r["p_mkt"] for r in c26), 4)],
        },
        "arm3a": {
            "unique_questions": len(q3a),
            "pairs_spread_ge_020": len(p3a),
            "pairs_strict_opposing": sum(1 for r in p3a if r["strict_opposing"]),
            "pairs_smollm2_eligible": sum(1 for r in p3a if r["eligible_smollm2"]),
            "individual_rationales": len(i3a),
        },
        "arm3b": {
            "unique_questions_2plus_preres": len(q3b),
            "pairs_yes_no_positioned": len(p3b),
            "pairs_by_y": dict(Counter(r["resolved_to"] for r in p3b)),
            "individual_comments": len(i3b),
        },
        "arm2": arm2_audit,
    }
    (OUT_DIR / "corpus_audit.json").write_text(json.dumps(corpus_audit, indent=2))

    # Write committed MANIFEST_CORPORA.json (hashes & counts only, no raw third-party text)
    manifest = {
        "counts": {
            "corpus_2026": len(c26),
            "arm2_arguments": len(c26) * 4,
            "arm3a_questions": len(q3a),
            "arm3a_pairs": len(p3a),
            "arm3a_individual": len(i3a),
            "arm3b_questions": len(q3b),
            "arm3b_pairs": len(p3b),
            "arm3b_individual": len(i3b),
        },
        "sha256": {
            fn: sha256_file(DATA_DIR / fn)
            for fn in [
                "corpus_2026.jsonl", "arm2_arguments.jsonl",
                "arm3a_questions.jsonl", "arm3a_pairs.jsonl", "arm3a_individual.jsonl",
                "arm3b_questions.jsonl", "arm3b_pairs.jsonl", "arm3b_individual.jsonl",
            ]
        },
    }
    (ROOT / "MANIFEST_CORPORA.json").write_text(json.dumps(manifest, indent=2))
    print(json.dumps(corpus_audit, indent=2))


if __name__ == "__main__":
    main()
