#!/usr/bin/env python3
"""Blind independent recompute and audit script for judges-postcutoff.

Computes all integrity/leakage audits, Arm 1, Arm 2, and Arm 3 metrics,
diagnostic checks, and frozen PLAN.md per-model / aggregate verdicts
strictly from pinned manifest/data files and code/text_baseline.py.
"""

from __future__ import annotations

import hashlib
import json
import math
import sys
from collections import Counter
from pathlib import Path
from typing import Any

import numpy as np
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import GroupKFold

REPRO_DIR = Path(__file__).resolve().parents[1]
DATA_DIR = REPRO_DIR / "data"
OUT_DIR = Path(__file__).resolve().parent

sys.path.insert(0, str(REPRO_DIR / "code"))
import text_baseline  # noqa: E402

MODELS = ("qwen2.5-1.5b", "smollm2-1.7b", "qwen3-4b-2507")
B_BOOT = 2000
SEED = 0


def sha256_file(path: Path) -> str:
    """Return hex SHA-256 digest of a file."""
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def load_jsonl(path: Path) -> list[dict[str, Any]]:
    """Load non-empty lines from a JSONL file."""
    with path.open("r", encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def sigmoid(x: np.ndarray | float) -> np.ndarray | float:
    """Numerically stable logistic sigmoid."""
    return 1.0 / (1.0 + np.exp(-np.clip(x, -40.0, 40.0)))


def logit(p: np.ndarray) -> np.ndarray:
    """Logit transform clipped away from 0 and 1."""
    pc = np.clip(p, 1e-6, 1.0 - 1e-6)
    return np.log(pc / (1.0 - pc))


def boot_mean_ci(arr: np.ndarray, b_draws: int = B_BOOT, seed: int = SEED) -> dict[str, Any]:
    """Compute sample mean and percentile 95% CI via i.i.d. bootstrap."""
    arr = np.asarray(arr, dtype=float)
    n = len(arr)
    if n == 0:
        return {"n": 0, "mean": None, "ci_lo": None, "ci_hi": None}
    rng = np.random.default_rng(seed)
    idx = rng.integers(0, n, size=(b_draws, n))
    means = arr[idx].mean(axis=1)
    lo, hi = np.percentile(means, [2.5, 97.5])
    return {"n": int(n), "mean": float(arr.mean()), "ci_lo": float(lo), "ci_hi": float(hi)}


def fit_ols_with_r2(x_mat: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, float]:
    """Fit OLS with intercept and return (slopes, R^2)."""
    xd = np.column_stack([np.ones(len(y)), x_mat])
    beta, _, _, _ = np.linalg.lstsq(xd, y, rcond=None)
    yhat = xd @ beta
    ss_res = float(np.sum((y - yhat) ** 2))
    ss_tot = float(np.sum((y - y.mean()) ** 2))
    r2 = 1.0 - ss_res / ss_tot if ss_tot > 0 else 0.0
    return beta[1:], r2


def standardize_once(x_raw: np.ndarray, y_raw: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Z-score predictors and outcome once across the full evaluation sample."""
    x_std = (x_raw - x_raw.mean(axis=0)) / x_raw.std(axis=0, ddof=0)
    y_std = (y_raw - y_raw.mean()) / y_raw.std(ddof=0)
    return x_std, y_std


def standardized_ols_bootstrap(
    x_raw: np.ndarray,
    y_raw: np.ndarray,
    col_names: list[str],
    cluster_ids: list[str] | None = None,
    b_draws: int = B_BOOT,
    seed: int = SEED,
) -> dict[str, Any]:
    """Run full-sample standardized OLS with leave-one-column-out partial R^2 and bootstrap CIs."""
    x_std, y_std = standardize_once(x_raw, y_raw)
    beta_full, r2_full = fit_ols_with_r2(x_std, y_std)

    partial_r2 = {}
    for j, name in enumerate(col_names):
        keep = [k for k in range(len(col_names)) if k != j]
        _, r2_red = fit_ols_with_r2(x_std[:, keep], y_std)
        partial_r2[name] = float((r2_full - r2_red) / (1.0 - r2_red)) if r2_red < 1.0 else 0.0

    rng = np.random.default_rng(seed)
    n = len(y_std)
    betas_b = np.zeros((b_draws, len(col_names)))
    r2_b = np.zeros(b_draws)

    if cluster_ids is None:
        for b in range(b_draws):
            idx = rng.integers(0, n, size=n)
            betas_b[b], r2_b[b] = fit_ols_with_r2(x_std[idx], y_std[idx])
    else:
        clusters: dict[str, list[int]] = {}
        for idx, cid in enumerate(cluster_ids):
            clusters.setdefault(cid, []).append(idx)
        c_keys = sorted(clusters.keys())
        nc = len(c_keys)
        for b in range(b_draws):
            chosen = rng.integers(0, nc, size=nc)
            idxs = [i for c in chosen for i in clusters[c_keys[c]]]
            betas_b[b], r2_b[b] = fit_ols_with_r2(x_std[idxs], y_std[idxs])

    lo, hi = np.percentile(betas_b, [2.5, 97.5], axis=0)
    r2_lo, r2_hi = np.percentile(r2_b, [2.5, 97.5])
    coeffs = {}
    for j, name in enumerate(col_names):
        coeffs[name] = {
            "beta": float(beta_full[j]),
            "ci_lo": float(lo[j]),
            "ci_hi": float(hi[j]),
            "partial_r2": partial_r2[name],
        }
    return {
        "n": int(n),
        "n_clusters": int(len(set(cluster_ids))) if cluster_ids is not None else int(n),
        "r2": float(r2_full),
        "r2_ci_lo": float(r2_lo),
        "r2_ci_hi": float(r2_hi),
        "predictors": coeffs,
    }


def cluster_boot_pearson(
    qids: list[str], x: np.ndarray, y: np.ndarray, b_draws: int = B_BOOT, seed: int = SEED
) -> dict[str, Any]:
    """Compute Pearson r and question-clustered bootstrap 95% CI."""
    r_obs = float(pearsonr(x, y)[0])
    clusters: dict[str, list[int]] = {}
    for idx, q in enumerate(qids):
        clusters.setdefault(q, []).append(idx)
    c_keys = sorted(clusters.keys())
    nc = len(c_keys)
    rng = np.random.default_rng(seed)
    vals = []
    for _ in range(b_draws):
        chosen = rng.integers(0, nc, size=nc)
        idxs = [i for c in chosen for i in clusters[c_keys[c]]]
        xi, yi = x[idxs], y[idxs]
        if xi.std() > 0 and yi.std() > 0:
            vals.append(float(pearsonr(xi, yi)[0]))
    lo, hi = np.percentile(vals, [2.5, 97.5])
    return {"n": int(len(x)), "n_clusters": int(nc), "r": r_obs, "ci_lo": float(lo), "ci_hi": float(hi)}


def group_kfold_tfidf_auroc(texts: list[str], y: np.ndarray, groups: list[str], repeats: int = 5, folds: int = 5) -> dict[str, Any]:
    """Diagnostic question-grouped CV TF-IDF AUROC to separate cluster memorization from label signal."""
    t_arr = np.array(texts, dtype=object)
    g_arr = np.array(groups, dtype=object)
    gkf = GroupKFold(n_splits=folds)
    s = np.zeros(len(y))
    # Shuffle group order deterministically across repeats for averaged OOF predictions
    uniq_g = sorted(set(groups))
    rng = np.random.default_rng(SEED)
    for _ in range(repeats):
        perm = {g: int(p) for g, p in zip(uniq_g, rng.permutation(len(uniq_g)))}
        g_perm = np.array([perm[g] for g in g_arr])
        for tr, te in gkf.split(t_arr, y, g_perm):
            s[te] += text_baseline.model().fit(list(t_arr[tr]), y[tr]).decision_function(list(t_arr[te]))
    s /= repeats
    auroc, lo, hi = text_baseline.auc_ci(y, s, n=B_BOOT, seed=SEED)
    return {"auroc": auroc, "ci_lo": lo, "ci_hi": hi}


def run_text_and_length_check(texts: list[str], y: np.ndarray, groups: list[str] | None = None) -> dict[str, Any]:
    """Run text_baseline 5x5 CV TF-IDF AUROC and word-length AUROC."""
    y = np.asarray(y, dtype=int)
    cv_s = text_baseline.cv_scores(texts, y, repeats=5, folds=5, seed=SEED)
    cv_auroc, cv_lo, cv_hi = text_baseline.auc_ci(y, cv_s, n=B_BOOT, seed=SEED)
    wcs = [len(t.split()) for t in texts]
    len_auroc = float(roc_auc_score(y, wcs))
    res: dict[str, Any] = {
        "n": int(len(y)),
        "n_pos": int(y.sum()),
        "tfidf_cv_auroc": float(cv_auroc),
        "tfidf_cv_ci_lo": float(cv_lo),
        "tfidf_cv_ci_hi": float(cv_hi),
        "length_auroc": len_auroc,
    }
    if groups is not None:
        res["tfidf_group_kfold"] = group_kfold_tfidf_auroc(texts, y, groups)
    return res


def audit_integrity_and_leakage(
    manifest: dict[str, Any],
    c26: list[dict[str, Any]],
    a2_args: list[dict[str, Any]],
    a3a_q: list[dict[str, Any]],
    a3a_p: list[dict[str, Any]],
    a3a_i: list[dict[str, Any]],
    a3b_q: list[dict[str, Any]],
    a3b_p: list[dict[str, Any]],
    a3b_i: list[dict[str, Any]],
    arm3_scores: list[dict[str, Any]],
) -> dict[str, Any]:
    """Audit SHA-256 digests, row counts, cutoff timestamps, length matching, and text baselines."""
    datasets_by_name = {
        "corpus_2026": c26,
        "arm2_arguments": a2_args,
        "arm3a_questions": a3a_q,
        "arm3a_pairs": a3a_p,
        "arm3a_individual": a3a_i,
        "arm3b_questions": a3b_q,
        "arm3b_pairs": a3b_p,
        "arm3b_individual": a3b_i,
    }

    sha_checks = {}
    for fname, expected_sha in manifest["sha256"].items():
        actual_sha = sha256_file(DATA_DIR / fname)
        assert actual_sha == expected_sha, f"SHA-256 mismatch for {fname}"
        stem = fname.replace(".jsonl", "")
        rows = datasets_by_name[stem]
        actual_count = sum(len(r["args"]) for r in rows) if stem == "arm2_arguments" else len(rows)
        expected_count = manifest["counts"][stem]
        assert actual_count == expected_count, f"Count mismatch for {fname}: {actual_count} != {expected_count}"
        sha_checks[fname] = {
            "sha256": actual_sha,
            "matches_manifest": True,
            "file_rows": len(rows),
            "manifest_count": actual_count,
            "expected_count": expected_count,
        }

    score_files_sha = {}
    for fname in ("priors_per_item.jsonl", "arm2_scores.jsonl", "arm3_scores.jsonl"):
        score_files_sha[fname] = {
            "sha256": sha256_file(DATA_DIR / fname),
            "rows": len(load_jsonl(DATA_DIR / fname)),
        }

    # Corpus-2026 checks
    c26_ids = [r["id"] for r in c26]
    assert len(set(c26_ids)) == 300, "Duplicate IDs in corpus_2026"
    src_bal = Counter((r["source"], r["resolved_to"]) for r in c26)
    expected_bal = {
        ("manifold", 1): 35,
        ("manifold", 0): 35,
        ("metaculus", 1): 35,
        ("metaculus", 0): 35,
        ("polymarket", 1): 80,
        ("polymarket", 0): 80,
    }
    assert dict(src_bal) == expected_bal, f"Unexpected source balance: {src_bal}"
    p_mkts = [r["p_mkt"] for r in c26]
    res_dates = [r["resolution_date"] for r in c26]
    assert all(0.10 <= p <= 0.90 for p in p_mkts), "p_mkt outside [0.10, 0.90]"
    assert all(d >= "2026-01-01" for d in res_dates), "resolution_date < 2026-01-01"
    assert all(r["resolved_to"] in (0, 1) for r in c26), "Non-binary resolved_to"

    c26_audit = {
        "n": len(c26),
        "unique_ids": len(set(c26_ids)),
        "source_balance": {f"{s}_Y{y}": cnt for (s, y), cnt in sorted(src_bal.items())},
        "p_mkt_min": float(min(p_mkts)),
        "p_mkt_max": float(max(p_mkts)),
        "resolution_date_min": min(res_dates),
        "resolution_date_max": max(res_dates),
        "all_checks_passed": True,
    }

    # Arm 3A cutoff audit across corpora and arm3_scores
    a3a_q_map = {r["id"]: r for r in a3a_q}
    a3a_p_map = {r["id"]: r for r in a3a_p}
    assert len(set(a3a_q_map)) == 150
    assert all(r["resolution_date"] >= "2024-10-01" for r in a3a_q if r["eligible_qwen25"])
    assert all(r["resolution_date"] >= "2024-12-01" for r in a3a_q if r["eligible_smollm2"])
    assert sum(1 for r in a3a_q if r["eligible_qwen25"]) == 150
    assert sum(1 for r in a3a_q if r["eligible_smollm2"]) == 40
    assert sum(1 for r in a3a_q if r["eligible_qwen3"]) == 3
    assert all(r["spread"] >= 0.20 - 1e-12 for r in a3a_p)
    assert all(r["more_accurate_side"] == ("high" if r["resolved_to"] == 1 else "low") for r in a3a_p)

    # Verify scored rows strictly respect cutoffs
    a3a_scored_audit = {}
    for m, flag, cutoff in [
        ("qwen2.5-1.5b", "eligible_qwen25", "2024-10-01"),
        ("smollm2-1.7b", "eligible_smollm2", "2024-12-01"),
        ("qwen3-4b-2507", "eligible_qwen3", "2025-09-01"),
    ]:
        p_rows = [r for r in arm3_scores if r["model"] == m and r["kind"] == "arm3a_pair"]
        i_rows = [r for r in arm3_scores if r["model"] == m and r["kind"] == "arm3a_ind"]
        if m == "qwen3-4b-2507":
            assert len(p_rows) == 0 and len(i_rows) == 0, "qwen3 must be excluded from Arm 3A"
        else:
            for r in p_rows:
                meta = a3a_p_map[r["id"]]
                assert meta[flag] and meta["resolution_date"] >= cutoff
            for r in i_rows:
                meta = a3a_q_map[r["id"]]
                assert meta[flag] and meta["resolution_date"] >= cutoff
        a3a_scored_audit[m] = {
            "cutoff_min_resolution_date": cutoff,
            "excluded": m == "qwen3-4b-2507",
            "n_pairs_scored": len(p_rows),
            "n_ind_scored": len(i_rows),
            "min_scored_resolution_date": (
                min(a3a_q_map[r["id"]]["resolution_date"] for r in i_rows) if i_rows else None
            ),
        }

    # Arm 3B timestamp and length audit
    seven_days_ms = 7 * 86400 * 1000
    bad_ind_ts = bad_ind_len = bad_pair_ts = bad_pair_len = 0
    for r in a3b_i:
        bound = min(r["freeze_ms"], r["resolution_ms"] - seven_days_ms)
        assert r["cutoff_ms"] == bound
        if not (r["created_ms"] < bound):
            bad_ind_ts += 1
        if len(r["text"]) < 100 or len(r["text_redacted"]) < 100:
            bad_ind_len += 1
    for r in a3b_p:
        bound = min(r["freeze_ms"], r["resolution_ms"] - seven_days_ms)
        assert r["cutoff_ms"] == bound
        assert r["more_accurate_side"] == ("YES" if r["resolved_to"] == 1 else "NO")
        assert r["yes_shares"] > 0 and r["no_shares"] > 0
        for side in ("yes", "no"):
            if not (r[f"{side}_created_ms"] < bound):
                bad_pair_ts += 1
            if len(r[f"{side}_text"]) < 100 or len(r[f"{side}_text_redacted"]) < 100:
                bad_pair_len += 1
    assert bad_ind_ts == 0 and bad_ind_len == 0 and bad_pair_ts == 0 and bad_pair_len == 0

    a3b_audit = {
        "n_questions": len(a3b_q),
        "n_pairs": len(a3b_p),
        "n_individual": len(a3b_i),
        "n_individual_positioned": sum(1 for r in a3b_i if r["position_outcome"] in ("YES", "NO")),
        "n_questions_positioned": len({r["id"] for r in a3b_i if r["position_outcome"] in ("YES", "NO")}),
        "bad_timestamp_count": 0,
        "bad_length_lt_100_count": 0,
        "min_char_len_ind_verbatim": min(len(r["text"]) for r in a3b_i),
        "min_char_len_ind_redacted": min(len(r["text_redacted"]) for r in a3b_i),
        "min_char_len_pair_verbatim": min(min(len(r["yes_text"]), len(r["no_text"])) for r in a3b_p),
        "min_char_len_pair_redacted": min(min(len(r["yes_text_redacted"]), len(r["no_text_redacted"])) for r in a3b_p),
        "min_resolution_date": min(r["resolution_date"] for r in a3b_q),
    }

    # Arm 2 word counts, length ratios, length AUROCs, and text_baseline per cell
    assert [r["id"] for r in sorted(a2_args, key=lambda x: x["id"])] == sorted(c26_ids)
    cells = ("YES_strong", "YES_weak", "NO_strong", "NO_weak")
    wc_mismatch = 0
    sw_outside = 0
    yn_outside = 0
    for r in a2_args:
        for cell in cells:
            if len(r["args"][cell].split()) != r["word_counts"][cell]:
                wc_mismatch += 1
        w = r["word_counts"]
        for side in ("YES", "NO"):
            if not (0.80 <= w[f"{side}_strong"] / w[f"{side}_weak"] <= 1.25):
                sw_outside += 1
        for qual in ("strong", "weak"):
            if not (0.80 <= w[f"YES_{qual}"] / w[f"NO_{qual}"] <= 1.25):
                yn_outside += 1

    y_c26 = np.array([r["resolved_to"] for r in a2_args], dtype=int)
    arm2_cells_audit = {}
    for cell in cells:
        texts = [r["args"][cell] for r in a2_args]
        wcs = [r["word_counts"][cell] for r in a2_args]
        tb = run_text_and_length_check(texts, y_c26)
        tb["mean_word_count"] = float(np.mean(wcs))
        tb["std_word_count"] = float(np.std(wcs, ddof=1))
        tb["min_word_count"] = int(min(wcs))
        tb["max_word_count"] = int(max(wcs))
        arm2_cells_audit[cell] = tb

    sw_wcs = [r["word_counts"][c] for c in ("YES_strong", "NO_strong", "YES_weak", "NO_weak") for r in a2_args]
    yn_wcs = [r["word_counts"][c] for c in ("YES_strong", "YES_weak", "NO_strong", "NO_weak") for r in a2_args]
    length_auroc_strong_vs_weak = float(roc_auc_score([1] * 600 + [0] * 600, sw_wcs))
    length_auroc_yes_vs_no = float(roc_auc_score([1] * 600 + [0] * 600, yn_wcs))

    arm2_text_audit = {
        "wc_split_mismatch": wc_mismatch,
        "strong_vs_weak_pairs_outside_0.80_1.25": sw_outside,
        "yes_vs_no_pairs_outside_0.80_1.25": yn_outside,
        "total_pairs_per_axis": 600,
        "length_auroc_strong_vs_weak": length_auroc_strong_vs_weak,
        "length_auroc_yes_vs_no": length_auroc_yes_vs_no,
        "cells_predicting_resolved_to": arm2_cells_audit,
    }

    # Arm 3 text & length-only baselines via text_baseline.py
    arm3_text_audit = {
        "arm3a_pair_high_verbatim_vs_resolved_to": run_text_and_length_check(
            [r["high_text"] for r in a3a_p], np.array([r["resolved_to"] for r in a3a_p])
        ),
        "arm3a_pair_low_verbatim_vs_resolved_to": run_text_and_length_check(
            [r["low_text"] for r in a3a_p], np.array([r["resolved_to"] for r in a3a_p])
        ),
        "arm3a_pair_high_redacted_vs_resolved_to": run_text_and_length_check(
            [r["high_text_redacted"] for r in a3a_p], np.array([r["resolved_to"] for r in a3a_p])
        ),
        "arm3a_pair_low_redacted_vs_resolved_to": run_text_and_length_check(
            [r["low_text_redacted"] for r in a3a_p], np.array([r["resolved_to"] for r in a3a_p])
        ),
        "arm3a_pair_pooled_more_accurate_verbatim": run_text_and_length_check(
            [r["high_text"] for r in a3a_p] + [r["low_text"] for r in a3a_p],
            np.array([int(r["more_accurate_side"] == "high") for r in a3a_p] + [int(r["more_accurate_side"] == "low") for r in a3a_p]),
        ),
        "arm3a_pair_pooled_more_accurate_redacted": run_text_and_length_check(
            [r["high_text_redacted"] for r in a3a_p] + [r["low_text_redacted"] for r in a3a_p],
            np.array([int(r["more_accurate_side"] == "high") for r in a3a_p] + [int(r["more_accurate_side"] == "low") for r in a3a_p]),
        ),
        "arm3b_pair_yes_verbatim_vs_resolved_to": run_text_and_length_check(
            [r["yes_text"] for r in a3b_p], np.array([r["resolved_to"] for r in a3b_p])
        ),
        "arm3b_pair_no_verbatim_vs_resolved_to": run_text_and_length_check(
            [r["no_text"] for r in a3b_p], np.array([r["resolved_to"] for r in a3b_p])
        ),
        "arm3b_pair_yes_redacted_vs_resolved_to": run_text_and_length_check(
            [r["yes_text_redacted"] for r in a3b_p], np.array([r["resolved_to"] for r in a3b_p])
        ),
        "arm3b_pair_no_redacted_vs_resolved_to": run_text_and_length_check(
            [r["no_text_redacted"] for r in a3b_p], np.array([r["resolved_to"] for r in a3b_p])
        ),
        "arm3b_pair_pooled_more_accurate_verbatim": run_text_and_length_check(
            [r["yes_text"] for r in a3b_p] + [r["no_text"] for r in a3b_p],
            np.array([int(r["more_accurate_side"] == "YES") for r in a3b_p] + [int(r["more_accurate_side"] == "NO") for r in a3b_p]),
        ),
        "arm3b_pair_pooled_more_accurate_redacted": run_text_and_length_check(
            [r["yes_text_redacted"] for r in a3b_p] + [r["no_text_redacted"] for r in a3b_p],
            np.array([int(r["more_accurate_side"] == "YES") for r in a3b_p] + [int(r["more_accurate_side"] == "NO") for r in a3b_p]),
        ),
        "arm3a_ind_verbatim_vs_resolved_to": run_text_and_length_check(
            [r["text"] for r in a3a_i],
            np.array([r["resolved_to"] for r in a3a_i]),
            groups=[r["id"] for r in a3a_i],
        ),
        "arm3a_ind_redacted_vs_resolved_to": run_text_and_length_check(
            [r["text_redacted"] for r in a3a_i],
            np.array([r["resolved_to"] for r in a3a_i]),
            groups=[r["id"] for r in a3a_i],
        ),
        "arm3a_ind_redacted_acc_gt_05": run_text_and_length_check(
            [r["text_redacted"] for r in a3a_i],
            np.array([int(r["accuracy"] > 0.5) for r in a3a_i]),
            groups=[r["id"] for r in a3a_i],
        ),
        "arm3b_ind_verbatim_vs_resolved_to": run_text_and_length_check(
            [r["text"] for r in a3b_i],
            np.array([r["resolved_to"] for r in a3b_i]),
            groups=[r["id"] for r in a3b_i],
        ),
        "arm3b_ind_redacted_vs_resolved_to": run_text_and_length_check(
            [r["text_redacted"] for r in a3b_i],
            np.array([r["resolved_to"] for r in a3b_i]),
            groups=[r["id"] for r in a3b_i],
        ),
        "arm3b_ind_positioned_redacted_accurate": run_text_and_length_check(
            [r["text_redacted"] for r in a3b_i if r["position_outcome"] in ("YES", "NO")],
            np.array([int((r["position_outcome"] == "YES") == (r["resolved_to"] == 1)) for r in a3b_i if r["position_outcome"] in ("YES", "NO")]),
            groups=[r["id"] for r in a3b_i if r["position_outcome"] in ("YES", "NO")],
        ),
    }

    return {
        "manifest_sha256": sha_checks,
        "score_files_sha256": score_files_sha,
        "corpus_2026": c26_audit,
        "arm3a_cutoffs": a3a_scored_audit,
        "arm3b_timestamps_and_lengths": a3b_audit,
        "arm2_text_and_length": arm2_text_audit,
        "arm3_text_and_length": arm3_text_audit,
    }


def compute_arm1(priors_all: list[dict[str, Any]], c26_ids: list[str]) -> dict[str, Any]:
    """Audit priors_per_item.jsonl (1,533 rows = 511 x 3) and compute per-model Arm 1 metrics on corpus_2026."""
    assert len(priors_all) == 1533
    by_model_count = Counter(r["model"] for r in priors_all)
    assert all(by_model_count[m] == 511 for m in MODELS)

    numeric_keys = ("ell_pos", "ell_neg", "l_prior", "p_prior", "acquiescence_bias", "mass_pos", "mass_neg")
    n_nan = sum(
        1
        for r in priors_all
        if any(r[k] is None or (isinstance(r[k], float) and math.isnan(r[k])) for k in numeric_keys)
    )
    n_ties = sum(1 for r in priors_all if r["l_prior"] == 0.0)
    assert n_nan == 0 and n_ties == 0

    max_lp_err = max(abs(r["l_prior"] - 0.5 * (r["ell_pos"] + r["ell_neg"])) for r in priors_all)
    max_acq_err = max(abs(r["acquiescence_bias"] - 0.5 * (r["ell_pos"] - r["ell_neg"])) for r in priors_all)
    max_pp_err = max(abs(r["p_prior"] - float(sigmoid(r["l_prior"]))) for r in priors_all)
    assert max_lp_err < 1e-5 and max_acq_err < 1e-5 and max_pp_err < 1e-5

    corpora_dist = Counter(tuple(r["corpora"]) for r in priors_all if r["model"] == MODELS[0])
    priors_map = {(r["model"], r["id"]): r for r in priors_all}
    c26_sorted = sorted(c26_ids)

    per_model = {}
    for m in MODELS:
        rows = [priors_map[(m, qid)] for qid in c26_sorted]
        y = np.array([r["resolved_to"] for r in rows], dtype=float)
        lp = np.array([r["l_prior"] for r in rows], dtype=float)
        pp = np.array([r["p_prior"] for r in rows], dtype=float)
        pmkt = np.array([r["p_mkt"] for r in rows], dtype=float)
        rc = np.array([r["prior_correct"] for r in rows], dtype=bool)
        mass_both = np.array([0.5 * (r["mass_pos"] + r["mass_neg"]) for r in rows], dtype=float)
        mass_min = np.array([min(r["mass_pos"], r["mass_neg"]) for r in rows], dtype=float)
        acq = np.array([r["acquiescence_bias"] for r in rows], dtype=float)

        # 60-item 0-100 probe (across all items with prob_raw != None)
        probe_raw = [r for r in priors_all if r["model"] == m and r["prob_raw"] is not None]
        probe_valid = [r for r in probe_raw if r["prob_0_100"] is not None]
        sp_0_100 = spearmanr(
            [r["p_prior"] for r in probe_valid],
            [r["prob_0_100"] for r in probe_valid],
        )

        per_model[m] = {
            "n": len(rows),
            "n_right_prior": int(rc.sum()),
            "n_wrong_prior": int((~rc).sum()),
            "prior_accuracy": float(rc.mean()),
            "auroc_prior_vs_truth": float(roc_auc_score(y, pp)),
            "brier_prior": float(np.mean((pp - y) ** 2)),
            "auroc_mkt_vs_truth": float(roc_auc_score(y, pmkt)),
            "brier_mkt": float(np.mean((pmkt - y) ** 2)),
            "spearman_prior_vs_mkt": float(spearmanr(pp, pmkt).statistic),
            "spearman_prior_vs_mkt_p": float(spearmanr(pp, pmkt).pvalue),
            "mean_valid_mass": float(mass_both.mean()),
            "mean_min_valid_mass": float(mass_min.mean()),
            "min_valid_mass": float(mass_min.min()),
            "mean_abs_acquiescence": float(np.abs(acq).mean()),
            "mean_signed_acquiescence": float(acq.mean()),
            "arm1_frac_prior_pos": float((lp >= 0).mean()),
            "arm1_mean_l_prior": float(lp.mean()),
            "probe_0_100": {
                "n_attempted": len(probe_raw),
                "n_parsed_valid": len(probe_valid),
                "spearman_r": float(sp_0_100.statistic),
                "spearman_p": float(sp_0_100.pvalue),
            },
        }

    return {
        "global_row_check": {
            "total_rows": len(priors_all),
            "unique_items_per_model": 511,
            "corpora_breakdown_per_model": {"+".join(k): v for k, v in sorted(corpora_dist.items())},
            "n_nan_or_null": n_nan,
            "n_ties_l_prior_eq_0": n_ties,
            "max_identity_err": {
                "l_prior": float(max_lp_err),
                "acquiescence_bias": float(max_acq_err),
                "p_prior": float(max_pp_err),
            },
        },
        "corpus_2026_per_model": per_model,
    }


def compute_arm2(
    arm2_scores: list[dict[str, Any]],
    a2_args: list[dict[str, Any]],
    priors_all: list[dict[str, Any]],
) -> dict[str, Any]:
    """Recompute all Arm 2 pointwise, pairwise, OLS horse-race, scale_reversal, and g100 metrics."""
    assert len(arm2_scores) == 900
    priors = {(r["model"], r["id"]): r for r in priors_all}
    args_map = {r["id"]: r for r in a2_args}
    ids = sorted(args_map.keys())
    assert len(ids) == 300

    cells = ("YES_strong", "YES_weak", "NO_strong", "NO_weak")
    results: dict[str, Any] = {}

    for m in MODELS:
        s2_map = {r["id"]: r for r in arm2_scores if r["model"] == m}
        assert sorted(s2_map.keys()) == ids

        lp = np.array([priors[(m, qid)]["l_prior"] for qid in ids], dtype=float)
        y = np.array([priors[(m, qid)]["resolved_to"] for qid in ids], dtype=float)
        pmkt = np.array([priors[(m, qid)]["p_mkt"] for qid in ids], dtype=float)
        right = np.array([priors[(m, qid)]["prior_correct"] for qid in ids], dtype=bool)
        wrong = ~right
        sgn = np.where(lp >= 0.0, 1.0, -1.0)

        # Pointwise metrics
        pointwise_res: dict[str, Any] = {}
        for cond in ("plain", "instructed", "hard_to_vary"):
            yes_s = np.array([s2_map[qid]["pointwise"]["YES_strong"][cond] for qid in ids])
            yes_w = np.array([s2_map[qid]["pointwise"]["YES_weak"][cond] for qid in ids])
            no_s = np.array([s2_map[qid]["pointwise"]["NO_strong"][cond] for qid in ids])
            no_w = np.array([s2_map[qid]["pointwise"]["NO_weak"][cond] for qid in ids])

            d_yn = 0.5 * (yes_s + yes_w) - 0.5 * (no_s + no_w)
            d_prior = d_yn * sgn
            mean_d_yn = float(d_yn.mean())
            d_prior_c = (d_yn - mean_d_yn) * sgn
            d_qual = 0.5 * (yes_s + no_s) - 0.5 * (yes_w + no_w)
            level_per_q = 0.25 * (yes_s + yes_w + no_s + no_w)

            masses = np.array(
                [s2_map[qid]["pointwise"][cell][f"{cond}_mass"] for qid in ids for cell in cells],
                dtype=float,
            )

            pointwise_res[cond] = {
                "delta_prior_all": boot_mean_ci(d_prior),
                "delta_prior_right": boot_mean_ci(d_prior[right]),
                "delta_prior_wrong": boot_mean_ci(d_prior[wrong]),
                "diagnostic_yes_offset": {
                    "mean_d_yn_all": mean_d_yn,
                    "mean_d_yn_Y1": float(d_yn[y == 1].mean()),
                    "mean_d_yn_Y0": float(d_yn[y == 0].mean()),
                    "delta_prior_all_centered": boot_mean_ci(d_prior_c),
                    "delta_prior_right_centered": boot_mean_ci(d_prior_c[right]),
                    "delta_prior_wrong_centered": boot_mean_ci(d_prior_c[wrong]),
                },
                "delta_qual": boot_mean_ci(d_qual),
                "delta_qual_YES_side": boot_mean_ci(yes_s - yes_w),
                "delta_qual_NO_side": boot_mean_ci(no_s - no_w),
                "mean_level": boot_mean_ci(level_per_q),
                "mean_valid_mass": float(masses.mean()),
                "min_valid_mass": float(masses.min()),
            }

        # Order-swapped pairwise metrics
        lo_s_yn = np.array([s2_map[qid]["pairwise"]["strong_yes_vs_no"]["logodds_1_over_2"] for qid in ids])
        lo_wy_sn = np.array([s2_map[qid]["pairwise"]["weak_yes_vs_strong_no"]["logodds_1_over_2"] for qid in ids])
        lo_wn_sy = np.array([s2_map[qid]["pairwise"]["weak_no_vs_strong_yes"]["logodds_1_over_2"] for qid in ids])

        lo_prior = lo_s_yn * sgn
        lo_prior_c = (lo_s_yn - float(lo_s_yn.mean())) * sgn

        # Conflict: Weak(Prior-Aligned) vs Strong(Prior-Contradicting)
        conf_lo = np.where(lp >= 0.0, lo_wy_sn, lo_wn_sy)
        conf_fail = (conf_lo > 0.0).astype(float)

        # Strong vs Weak beats rates (tie=0.5)
        sn_beats_wy = np.where(lo_wy_sn < 0.0, 1.0, np.where(lo_wy_sn == 0.0, 0.5, 0.0))
        sy_beats_wn = np.where(lo_wn_sy < 0.0, 1.0, np.where(lo_wn_sy == 0.0, 0.5, 0.0))

        pw_mass_by_type = {}
        all_pw_mass = []
        for pk in ("strong_yes_vs_no", "weak_yes_vs_strong_no", "weak_no_vs_strong_yes"):
            mm = np.array([s2_map[qid]["pairwise"][pk]["mass_min"] for qid in ids], dtype=float)
            all_pw_mass.append(mm)
            pw_mass_by_type[pk] = {"mean": float(mm.mean()), "min": float(mm.min())}
        all_pw_mass_flat = np.concatenate(all_pw_mass)

        pairwise_res = {
            "strong_yes_vs_no": {
                "mean_logodds_yes_over_no": boot_mean_ci(lo_s_yn),
                "logodds_prior_all": boot_mean_ci(lo_prior),
                "logodds_prior_right": boot_mean_ci(lo_prior[right]),
                "logodds_prior_wrong": boot_mean_ci(lo_prior[wrong]),
                "logodds_prior_all_centered": boot_mean_ci(lo_prior_c),
                "logodds_prior_right_centered": boot_mean_ci(lo_prior_c[right]),
                "logodds_prior_wrong_centered": boot_mean_ci(lo_prior_c[wrong]),
            },
            "conflict_weak_prior_vs_strong_contra": {
                "fail_rate_all": boot_mean_ci(conf_fail),
                "fail_rate_right": boot_mean_ci(conf_fail[right]),
                "fail_rate_wrong": boot_mean_ci(conf_fail[wrong]),
                "margin_all": boot_mean_ci(conf_lo),
                "margin_wrong": boot_mean_ci(conf_lo[wrong]),
                "margin_right": boot_mean_ci(conf_lo[right]),
            },
            "pairwise_strong_vs_weak": {
                "strong_no_beats_weak_yes_rate": boot_mean_ci(sn_beats_wy),
                "strong_yes_beats_weak_no_rate": boot_mean_ci(sy_beats_wn),
                "mean_logodds_strong_no_over_weak_yes": boot_mean_ci(-lo_wy_sn),
                "mean_logodds_strong_yes_over_weak_no": boot_mean_ci(-lo_wn_sy),
                "mean_logodds_strong_over_weak_avg": boot_mean_ci(0.5 * (-lo_wy_sn - lo_wn_sy)),
            },
            "mass_min_stats": {
                "overall_mean": float(all_pw_mass_flat.mean()),
                "overall_min": float(all_pw_mass_flat.min()),
                "by_comparison": pw_mass_by_type,
            },
        }

        # Horse-race standardized OLS regressions
        r_len = np.array(
            [
                math.log(
                    (args_map[qid]["word_counts"]["YES_strong"] + args_map[qid]["word_counts"]["YES_weak"])
                    / (args_map[qid]["word_counts"]["NO_strong"] + args_map[qid]["word_counts"]["NO_weak"])
                )
                for qid in ids
            ],
            dtype=float,
        )
        x_hr = np.column_stack([lp, y - 0.5, logit(pmkt), r_len])
        hr_cols = ["l_prior", "truth", "logit_p_mkt", "log_wc_ratio"]
        horse_race = {}
        for cond in ("plain", "instructed", "hard_to_vary", "pairwise_strong"):
            if cond == "pairwise_strong":
                y_reg = lo_s_yn
            else:
                y_reg = np.array(
                    [
                        0.5 * (s2_map[qid]["pointwise"]["YES_strong"][cond] + s2_map[qid]["pointwise"]["YES_weak"][cond])
                        - 0.5 * (s2_map[qid]["pointwise"]["NO_strong"][cond] + s2_map[qid]["pointwise"]["NO_weak"][cond])
                        for qid in ids
                    ],
                    dtype=float,
                )
            horse_race[cond] = standardized_ols_bootstrap(x_hr, y_reg, hr_cols)

        # Sub-100 scale_reversal and g100_bridge checks
        sub_ids = [qid for qid in ids if s2_map[qid]["in_sub100"]]
        assert len(sub_ids) == 100
        sub_wrong = np.array([not priors[(m, qid)]["prior_correct"] for qid in sub_ids], dtype=bool)
        sub_sgn = np.array([1.0 if priors[(m, qid)]["l_prior"] >= 0 else -1.0 for qid in sub_ids], dtype=float)

        norm_cells = []
        plain_cells = []
        sr_aligned_cells = []
        sr_raw_cells = []
        sr_mass_cells = []
        for qid in sub_ids:
            for cell in cells:
                c = s2_map[qid]["pointwise"][cell]
                norm_cells.append(c["instructed"])
                plain_cells.append(c["plain"])
                sr_aligned_cells.append(c["scale_rev_aligned"])
                sr_raw_cells.append(c["scale_rev_raw"])
                sr_mass_cells.append(c["scale_rev_mass"])

        d_yn_norm_sub = np.array(
            [
                0.5 * (s2_map[qid]["pointwise"]["YES_strong"]["instructed"] + s2_map[qid]["pointwise"]["YES_weak"]["instructed"])
                - 0.5 * (s2_map[qid]["pointwise"]["NO_strong"]["instructed"] + s2_map[qid]["pointwise"]["NO_weak"]["instructed"])
                for qid in sub_ids
            ]
        )
        d_yn_sr_sub = np.array(
            [
                0.5 * (s2_map[qid]["pointwise"]["YES_strong"]["scale_rev_aligned"] + s2_map[qid]["pointwise"]["YES_weak"]["scale_rev_aligned"])
                - 0.5 * (s2_map[qid]["pointwise"]["NO_strong"]["scale_rev_aligned"] + s2_map[qid]["pointwise"]["NO_weak"]["scale_rev_aligned"])
                for qid in sub_ids
            ]
        )
        d_qual_norm_sub = np.array(
            [
                0.5 * (s2_map[qid]["pointwise"]["YES_strong"]["instructed"] + s2_map[qid]["pointwise"]["NO_strong"]["instructed"])
                - 0.5 * (s2_map[qid]["pointwise"]["YES_weak"]["instructed"] + s2_map[qid]["pointwise"]["NO_weak"]["instructed"])
                for qid in sub_ids
            ]
        )
        d_qual_sr_sub = np.array(
            [
                0.5 * (s2_map[qid]["pointwise"]["YES_strong"]["scale_rev_aligned"] + s2_map[qid]["pointwise"]["NO_strong"]["scale_rev_aligned"])
                - 0.5 * (s2_map[qid]["pointwise"]["YES_weak"]["scale_rev_aligned"] + s2_map[qid]["pointwise"]["NO_weak"]["scale_rev_aligned"])
                for qid in sub_ids
            ]
        )

        # g100 bridge (200 cells per prompt: YES_strong, NO_strong)
        g100_bridge = {}
        for prompt_key, g100_key in (("plain", "g100_plain"), ("instructed", "g100_inst")):
            e15_vals, g100_vals = [], []
            for qid in sub_ids:
                for cell in ("YES_strong", "NO_strong"):
                    c = s2_map[qid]["pointwise"][cell]
                    if c.get(g100_key) is not None:
                        e15_vals.append(c[prompt_key])
                        g100_vals.append(c[g100_key])
            sp = spearmanr(e15_vals, g100_vals)
            g100_bridge[prompt_key] = {
                "n_valid_cells": len(g100_vals),
                "mean_e15": float(np.mean(e15_vals)),
                "mean_g100": float(np.mean(g100_vals)),
                "spearman_r": float(sp.statistic),
                "spearman_p": float(sp.pvalue),
            }

        scale_reversal = {
            "n_questions": len(sub_ids),
            "n_cells": len(norm_cells),
            "spearman_norm_inst_vs_scale_rev_aligned": float(spearmanr(norm_cells, sr_aligned_cells).statistic),
            "spearman_norm_inst_vs_scale_rev_raw": float(spearmanr(norm_cells, sr_raw_cells).statistic),
            "spearman_norm_plain_vs_scale_rev_aligned": float(spearmanr(plain_cells, sr_aligned_cells).statistic),
            "mean_norm_instructed": float(np.mean(norm_cells)),
            "mean_scale_rev_aligned": float(np.mean(sr_aligned_cells)),
            "mean_scale_rev_raw": float(np.mean(sr_raw_cells)),
            "mean_shift_raw_minus_norm": float(np.mean(sr_raw_cells) - np.mean(norm_cells)),
            "mean_shift_aligned_minus_norm": float(np.mean(sr_aligned_cells) - np.mean(norm_cells)),
            "mean_scale_rev_mass": float(np.mean(sr_mass_cells)),
            "min_scale_rev_mass": float(np.min(sr_mass_cells)),
            "delta_prior_wrong_norm_sub100": boot_mean_ci((d_yn_norm_sub * sub_sgn)[sub_wrong]),
            "delta_prior_wrong_scale_rev_aligned_sub100": boot_mean_ci((d_yn_sr_sub * sub_sgn)[sub_wrong]),
            "delta_qual_norm_sub100": boot_mean_ci(d_qual_norm_sub),
            "delta_qual_scale_rev_aligned_sub100": boot_mean_ci(d_qual_sr_sub),
        }

        results[m] = {
            "pointwise": pointwise_res,
            "pairwise": pairwise_res,
            "horse_race_ols": horse_race,
            "scale_reversal_sub100": scale_reversal,
            "g100_bridge_sub100": g100_bridge,
        }

    return results


def eval_arm3_pair_subset(
    model: str,
    rows: list[dict[str, Any]],
    priors: dict[tuple[str, str], dict[str, Any]],
    a3a_p: dict[str, dict[str, Any]],
    a3b_p: dict[str, dict[str, Any]],
) -> dict[str, Any]:
    """Compute Arm 3 pairwise accuracy, prior_match, length_only_acc, mass_min, and OLS (if n>=15)."""
    n = len(rows)
    if n == 0:
        return {"n": 0}
    right = np.array([priors[(model, r["id"])]["prior_correct"] for r in rows], dtype=bool)
    wrong = ~right
    lp = np.array([priors[(model, r["id"])]["l_prior"] for r in rows], dtype=float)
    truth = np.array([r["resolved_to"] - 0.5 for r in rows], dtype=float)
    qids = [r["id"] for r in rows]

    out: dict[str, Any] = {
        "n": int(n),
        "n_right_prior": int(right.sum()),
        "n_wrong_prior": int(wrong.sum()),
        "conditions": {},
    }

    for cond in ("inst_verbatim", "inst_redacted", "htv_redacted"):
        acc = []
        pm_bin = []
        pm_dist = []
        len_acc = []
        masses = []
        y_reg = []
        log_len_ratio = []
        is_verbatim = cond == "inst_verbatim"

        for r in rows:
            p = priors[(model, r["id"])]
            lo = r[cond]["logodds_1_over_2"]
            masses.append(r[cond]["mass_min"])
            y_reg.append(lo)

            if r["kind"] == "arm3a_pair":
                s1, s2 = "high", "low"
                ap = a3a_p[r["id"]]
                t1 = ap["high_text"] if is_verbatim else ap["high_text_redacted"]
                t2 = ap["low_text"] if is_verbatim else ap["low_text_redacted"]
                dist_side = (
                    "high"
                    if abs(p["p_prior"] - ap["high_forecast"]) < abs(p["p_prior"] - ap["low_forecast"])
                    else "low"
                )
            else:
                s1, s2 = "YES", "NO"
                ap = a3b_p[r["id"]]
                t1 = ap["yes_text"] if is_verbatim else ap["yes_text_redacted"]
                t2 = ap["no_text"] if is_verbatim else ap["no_text_redacted"]
                dist_side = None

            w1, w2 = max(len(t1.split()), 1), max(len(t2.split()), 1)
            log_len_ratio.append(math.log(w1 / w2))

            pref = s1 if lo > 0 else (s2 if lo < 0 else "tie")
            acc.append(0.5 if pref == "tie" else float(pref == r["more_accurate_side"]))

            bin_side = s1 if p["l_prior"] >= 0 else s2
            pm_bin.append(0.5 if pref == "tie" else float(pref == bin_side))
            if dist_side is not None:
                pm_dist.append(0.5 if pref == "tie" else float(pref == dist_side))

            lpref = s1 if w1 > w2 else (s2 if w2 > w1 else "tie")
            len_acc.append(0.5 if lpref == "tie" else float(lpref == r["more_accurate_side"]))

        acc_arr = np.array(acc, dtype=float)
        pm_bin_arr = np.array(pm_bin, dtype=float)
        cond_res: dict[str, Any] = {
            "acc_all": boot_mean_ci(acc_arr),
            "acc_right_prior": boot_mean_ci(acc_arr[right]),
            "acc_wrong_prior": boot_mean_ci(acc_arr[wrong]),
            "prior_match": boot_mean_ci(pm_bin_arr),
            "length_only_acc": float(np.mean(len_acc)),
            "mass_min_mean": float(np.mean(masses)),
            "mass_min_min": float(np.min(masses)),
            "n_ties": int(sum(1 for r in rows if r[cond]["logodds_1_over_2"] == 0.0)),
        }
        if len(pm_dist) == n:
            cond_res["prior_match_forecast_dist"] = boot_mean_ci(np.array(pm_dist, dtype=float))
        if n >= 15:
            x_mat = np.column_stack([lp, truth, np.array(log_len_ratio, dtype=float)])
            cond_res["ols"] = standardized_ols_bootstrap(
                x_mat,
                np.array(y_reg, dtype=float),
                ["l_prior", "truth", "log_len_ratio"],
                cluster_ids=qids,
            )
        out["conditions"][cond] = cond_res

    return out


def eval_arm3_individual(
    model: str,
    arm3_scores: list[dict[str, Any]],
    priors: dict[tuple[str, str], dict[str, Any]],
) -> dict[str, Any]:
    """Compute question-clustered Pearson correlations and standardized OLS on Arm 3A/3B individual items."""
    out: dict[str, Any] = {}

    # Arm 3A individual
    r3a = [r for r in arm3_scores if r["model"] == model and r["kind"] == "arm3a_ind"]
    if r3a:
        qids = [r["id"] for r in r3a]
        acc = np.array([r["accuracy"] for r in r3a], dtype=float)
        log_len = np.log(np.maximum([r["word_count"] for r in r3a], 1))
        pa_dist = np.array([1.0 - abs(priors[(model, r["id"])]["p_prior"] - r["forecast"]) for r in r3a], dtype=float)
        pa_lp = np.array([(2.0 * r["forecast"] - 1.0) * priors[(model, r["id"])]["l_prior"] for r in r3a], dtype=float)
        pa_sgn = np.array(
            [(2.0 * r["forecast"] - 1.0) * (1.0 if priors[(model, r["id"])]["l_prior"] >= 0 else -1.0) for r in r3a],
            dtype=float,
        )

        conds_3a = {}
        for cond in ("inst_verbatim", "inst_redacted", "htv_redacted"):
            sc = np.array([r[cond] for r in r3a], dtype=float)
            masses = np.array([r[f"{cond}_mass"] for r in r3a], dtype=float)
            conds_3a[cond] = {
                "mean_score": float(sc.mean()),
                "mass_mean": float(masses.mean()),
                "mass_min": float(masses.min()),
                "pearson_clustered": {
                    "accuracy": cluster_boot_pearson(qids, sc, acc),
                    "prior_agreement_1_minus_abs_diff": cluster_boot_pearson(qids, sc, pa_dist),
                    "prior_agreement_signed_l_prior": cluster_boot_pearson(qids, sc, pa_lp),
                    "prior_agreement_signed_bin": cluster_boot_pearson(qids, sc, pa_sgn),
                    "log_length": cluster_boot_pearson(qids, sc, log_len),
                },
                "ols_prior_1_minus_abs_diff": standardized_ols_bootstrap(
                    np.column_stack([pa_dist, acc, log_len]),
                    sc,
                    ["prior_agreement", "accuracy", "log_length"],
                    cluster_ids=qids,
                ),
                "ols_prior_signed_l_prior": standardized_ols_bootstrap(
                    np.column_stack([pa_lp, acc, log_len]),
                    sc,
                    ["prior_agreement_signed_l_prior", "accuracy", "log_length"],
                    cluster_ids=qids,
                ),
            }
        out["arm3a_ind"] = {
            "n": len(r3a),
            "n_questions": len(set(qids)),
            "conditions": conds_3a,
        }
    else:
        out["arm3a_ind"] = {"n": 0, "excluded": True}

    # Arm 3B individual (positioned subset = 204 items across 88 questions; also report total 294 log_length)
    r3b_all = [r for r in arm3_scores if r["model"] == model and r["kind"] == "arm3b_ind"]
    r3b_pos = [r for r in r3b_all if r["position_outcome"] in ("YES", "NO")]
    qids_all = [r["id"] for r in r3b_all]
    qids_pos = [r["id"] for r in r3b_pos]
    log_len_all = np.log(np.maximum([r["word_count"] for r in r3b_all], 1))

    pos_sign = np.array([1.0 if r["position_outcome"] == "YES" else -1.0 for r in r3b_pos], dtype=float)
    pos_01 = np.array([1.0 if r["position_outcome"] == "YES" else 0.0 for r in r3b_pos], dtype=float)
    truth_align = np.array(
        [1.0 if (r["position_outcome"] == "YES") == (r["resolved_to"] == 1) else 0.0 for r in r3b_pos],
        dtype=float,
    )
    pa_sgn = np.array(
        [pos_sign[i] * (1.0 if priors[(model, r["id"])]["l_prior"] >= 0 else -1.0) for i, r in enumerate(r3b_pos)],
        dtype=float,
    )
    pa_lp = np.array(
        [pos_sign[i] * priors[(model, r["id"])]["l_prior"] for i, r in enumerate(r3b_pos)],
        dtype=float,
    )
    pa_prob = np.array(
        [1.0 - abs(priors[(model, r["id"])]["p_prior"] - pos_01[i]) for i, r in enumerate(r3b_pos)],
        dtype=float,
    )
    log_len_pos = np.log(np.maximum([r["word_count"] for r in r3b_pos], 1))

    conds_3b = {}
    for cond in ("inst_verbatim", "inst_redacted", "htv_redacted"):
        sc_all = np.array([r[cond] for r in r3b_all], dtype=float)
        sc_pos = np.array([r[cond] for r in r3b_pos], dtype=float)
        masses_all = np.array([r[f"{cond}_mass"] for r in r3b_all], dtype=float)
        conds_3b[cond] = {
            "mean_score_all294": float(sc_all.mean()),
            "mass_mean_all294": float(masses_all.mean()),
            "mass_min_all294": float(masses_all.min()),
            "pearson_clustered_all294_log_length": cluster_boot_pearson(qids_all, sc_all, log_len_all),
            "pearson_clustered_positioned": {
                "truth_alignment": cluster_boot_pearson(qids_pos, sc_pos, truth_align),
                "prior_agreement_sgn": cluster_boot_pearson(qids_pos, sc_pos, pa_sgn),
                "prior_agreement_l_prior": cluster_boot_pearson(qids_pos, sc_pos, pa_lp),
                "prior_agreement_1_minus_abs_diff": cluster_boot_pearson(qids_pos, sc_pos, pa_prob),
                "log_length": cluster_boot_pearson(qids_pos, sc_pos, log_len_pos),
            },
            "ols_positioned_sgn": standardized_ols_bootstrap(
                np.column_stack([pa_sgn, truth_align, log_len_pos]),
                sc_pos,
                ["prior_agreement", "truth_alignment", "log_length"],
                cluster_ids=qids_pos,
            ),
            "ols_positioned_l_prior": standardized_ols_bootstrap(
                np.column_stack([pa_lp, truth_align, log_len_pos]),
                sc_pos,
                ["prior_agreement_l_prior", "truth_alignment", "log_length"],
                cluster_ids=qids_pos,
            ),
        }

    out["arm3b_ind"] = {
        "n_total": len(r3b_all),
        "n_total_questions": len(set(qids_all)),
        "n_positioned": len(r3b_pos),
        "n_positioned_questions": len(set(qids_pos)),
        "conditions": conds_3b,
    }
    return out


def classify_verdict(arm2_m: dict[str, Any], arm3_m: dict[str, Any], use_centered_delta: bool = False) -> dict[str, Any]:
    """Apply frozen PLAN.md H1/H2/H3/Unsettled verdict criteria."""
    inst = arm2_m["pointwise"]["instructed"]
    if use_centered_delta:
        dp_wrong = inst["diagnostic_yes_offset"]["delta_prior_wrong_centered"]
    else:
        dp_wrong = inst["delta_prior_wrong"]
    d_qual = inst["delta_qual"]
    hr = arm2_m["horse_race_ols"]["instructed"]["predictors"]
    b_prior = hr["l_prior"]
    b_truth = hr["truth"]
    r_wrong = arm3_m["combined_postcutoff_pairs"]["conditions"]["inst_redacted"]["acc_wrong_prior"]

    prejudice_survives = bool(
        (dp_wrong["ci_lo"] > 0.0)
        or (b_prior["ci_lo"] > 0.0 and b_prior["beta"] > b_truth["beta"])
    )
    has_truth_signal = bool(
        (r_wrong["ci_lo"] > 0.50 and r_wrong["mean"] > 0.55)
        or (b_truth["ci_lo"] > 0.0)
    )

    truth_ci_includes_zero = bool(b_truth["ci_lo"] <= 0.0 <= b_truth["ci_hi"])
    truth_small_rel_prior = bool(abs(b_truth["beta"]) < 0.25 * abs(b_prior["beta"]))

    if (
        dp_wrong["ci_lo"] > 0.0
        and b_prior["ci_lo"] > 0.0
        and (not has_truth_signal)
        and (truth_ci_includes_zero or truth_small_rel_prior)
    ):
        verdict = "H1 (Prior Prejudice)"
    elif (
        (not prejudice_survives)
        and has_truth_signal
        and d_qual["ci_lo"] > 0.0
        and (b_truth["beta"] >= b_prior["beta"] or r_wrong["ci_lo"] > 0.50)
    ):
        verdict = "H2 (Truth-Tracking / Prejudice-Resistant)"
    elif prejudice_survives and (has_truth_signal or d_qual["ci_lo"] > 0.0):
        verdict = "H3 (Partial Signal + Surviving Prejudice)"
    else:
        verdict = "Unsettled"

    return {
        "verdict": verdict,
        "prejudice_survives": prejudice_survives,
        "has_truth_signal": has_truth_signal,
        "inputs": {
            "delta_prior_wrong": dp_wrong,
            "delta_qual": d_qual,
            "beta_prior": b_prior,
            "beta_truth": b_truth,
            "R_wrong_inst_redacted": r_wrong,
        },
    }


def main() -> None:
    manifest = json.loads((REPRO_DIR / "MANIFEST_CORPORA.json").read_text(encoding="utf-8"))
    c26 = load_jsonl(DATA_DIR / "corpus_2026.jsonl")
    a2_args = load_jsonl(DATA_DIR / "arm2_arguments.jsonl")
    a3a_q = load_jsonl(DATA_DIR / "arm3a_questions.jsonl")
    a3a_p = load_jsonl(DATA_DIR / "arm3a_pairs.jsonl")
    a3a_i = load_jsonl(DATA_DIR / "arm3a_individual.jsonl")
    a3b_q = load_jsonl(DATA_DIR / "arm3b_questions.jsonl")
    a3b_p = load_jsonl(DATA_DIR / "arm3b_pairs.jsonl")
    a3b_i = load_jsonl(DATA_DIR / "arm3b_individual.jsonl")
    priors_all = load_jsonl(DATA_DIR / "priors_per_item.jsonl")
    arm2_scores = load_jsonl(DATA_DIR / "arm2_scores.jsonl")
    arm3_scores = load_jsonl(DATA_DIR / "arm3_scores.jsonl")

    audit = audit_integrity_and_leakage(
        manifest, c26, a2_args, a3a_q, a3a_p, a3a_i, a3b_q, a3b_p, a3b_i, arm3_scores
    )
    arm1 = compute_arm1(priors_all, [r["id"] for r in c26])
    arm2 = compute_arm2(arm2_scores, a2_args, priors_all)

    priors_map = {(r["model"], r["id"]): r for r in priors_all}
    a3a_p_map = {r["id"]: r for r in a3a_p}
    a3b_p_map = {r["id"]: r for r in a3b_p}

    arm3 = {}
    for m in MODELS:
        r3a_p = [r for r in arm3_scores if r["model"] == m and r["kind"] == "arm3a_pair"]
        r3b_p = [r for r in arm3_scores if r["model"] == m and r["kind"] == "arm3b_pair"]
        comb_p = r3a_p + r3b_p
        arm3[m] = {
            "arm3a_pairs": eval_arm3_pair_subset(m, r3a_p, priors_map, a3a_p_map, a3b_p_map),
            "arm3b_pairs": eval_arm3_pair_subset(m, r3b_p, priors_map, a3a_p_map, a3b_p_map),
            "combined_postcutoff_pairs": eval_arm3_pair_subset(m, comb_p, priors_map, a3a_p_map, a3b_p_map),
            "individual": eval_arm3_individual(m, arm3_scores, priors_map),
        }

    verdicts_frozen = {m: classify_verdict(arm2[m], arm3[m], use_centered_delta=False) for m in MODELS}
    verdicts_centered_diag = {m: classify_verdict(arm2[m], arm3[m], use_centered_delta=True) for m in MODELS}
    tally = Counter(v["verdict"] for v in verdicts_frozen.values())
    majority_verdict = next((k for k, cnt in tally.items() if cnt >= 2), "No >=2/3 majority")

    out = {
        "meta": {
            "seed": SEED,
            "bootstrap_draws": B_BOOT,
            "models": list(MODELS),
        },
        "audit": audit,
        "arm1": arm1,
        "arm2": arm2,
        "arm3": arm3,
        "verdicts": {
            "frozen_plan_rule": verdicts_frozen,
            "centered_delta_prior_sensitivity": verdicts_centered_diag,
            "tally": dict(tally),
            "workspace_majority_verdict": majority_verdict,
        },
    }

    out_path = OUT_DIR / "RECOMPUTED.json"
    out_path.write_text(json.dumps(out, indent=2) + "\n", encoding="utf-8")
    print(f"Wrote {out_path.name} ({out_path.stat().st_size} bytes)")
    print("Verdict tally:", dict(tally), "-> Majority:", majority_verdict)
    for m in MODELS:
        vf = verdicts_frozen[m]
        vc = verdicts_centered_diag[m]
        print(
            f"  {m:13s}: frozen={vf['verdict']} | centered_diag={vc['verdict']} | "
            f"dp_w={vf['inputs']['delta_prior_wrong']['mean']:.4f} "
            f"[{vf['inputs']['delta_prior_wrong']['ci_lo']:.4f},{vf['inputs']['delta_prior_wrong']['ci_hi']:.4f}] | "
            f"b_prior={vf['inputs']['beta_prior']['beta']:.4f} "
            f"[{vf['inputs']['beta_prior']['ci_lo']:.4f},{vf['inputs']['beta_prior']['ci_hi']:.4f}] | "
            f"b_truth={vf['inputs']['beta_truth']['beta']:.4f} "
            f"[{vf['inputs']['beta_truth']['ci_lo']:.4f},{vf['inputs']['beta_truth']['ci_hi']:.4f}] | "
            f"R_wrong={vf['inputs']['R_wrong_inst_redacted']['mean']:.4f} "
            f"[{vf['inputs']['R_wrong_inst_redacted']['ci_lo']:.4f},{vf['inputs']['R_wrong_inst_redacted']['ci_hi']:.4f}]"
        )


if __name__ == "__main__":
    main()
