#!/usr/bin/env python3
"""Independent blind statistical recompute for 20261123-hard-to-vary-pre-run-audit.

Clean-room implementation built strictly from PLAN.md, PLAN.v2.md, PLAN.v3.md,
INPUTS_sha256.txt, raw CSV inputs, and raw JSONL rollout logs.
"""

from __future__ import annotations

import csv
import hashlib
import json
import os
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

import numpy as np
from scipy.stats import binomtest, spearmanr
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupKFold
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

STUDY_DIR = Path(__file__).resolve().parent.parent
LOCAL_V0_DIR = STUDY_DIR.parent.parent / "files" / "hard-to-vary"
DEFAULT_BLOG_DIR = Path.home() / "z" / "blog"
if "HTV_BLOG_DIR" in os.environ:
    BLOG_HTV_DIR = Path(os.environ["HTV_BLOG_DIR"]).expanduser() / "public" / "files" / "hard-to-vary"
elif (LOCAL_V0_DIR / "items-v0.csv").exists():
    BLOG_HTV_DIR = LOCAL_V0_DIR
else:
    BLOG_HTV_DIR = DEFAULT_BLOG_DIR / "public" / "files" / "hard-to-vary"

MODELS = ["qwen3-4b", "mistral-7b", "llama3-3b"]
PROTOCOLS = ["P_naive", "P_v0", "P_counterfactual"]
ARMS = [
    "tight_short",
    "easy_long",
    "specificity_stuffed",
    "postulate_law",
    "opposite_compatible",
]
ANCHORED_ARMS = ["tight_short", "easy_long", "opposite_compatible"]

# Exact regex from PLAN.md (line 17)
PLAN_CONNECTOR_RE = re.compile(
    r"(?i)(,\s*so\b|\bbecause\b|\btherefore\b|\bso that\b|\buntil\b|\bwhereas\b)"
)
# Broader regex noted in review prompt for sensitivity comparison
ALT_CONNECTOR_RE = re.compile(
    r"(?i)\b(because|since|so|therefore|thus|hence|which|by|as)\b"
)

# Exact score extraction regexes from PLAN.md (line 55)
SCORE_LINE_RE = re.compile(r"(?im)^\s*(?:\*\*)?Score(?:\*\*)?\s*:\s*([1-5])\b")
SCORE_FALLBACK_RE = re.compile(r"(?i)\bScore\s*[:=]\s*([1-5])\b")
TAG_RE = re.compile(r"[\[(](FREE|BOUND|OPPOSITE|NONE)[\])]", re.IGNORECASE)


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def parse_expected_hashes(sha_file: Path) -> dict[str, str]:
    expected: dict[str, str] = {}
    for line in sha_file.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        parts = line.split(None, 1)
        if len(parts) == 2 and len(parts[0]) == 64:
            digest, label = parts[0], parts[1].strip()
            name = Path(label.split(" (", 1)[0]).name
            expected[name] = digest
    return expected


def verify_inputs() -> dict[str, Any]:
    expected = parse_expected_hashes(STUDY_DIR / "INPUTS_sha256.txt")
    targets = {
        "items-v0.csv": (BLOG_HTV_DIR / "items-v0.csv", "~/z/blog/public/files/hard-to-vary/items-v0.csv"),
        "key-v0.csv": (BLOG_HTV_DIR / "key-v0.csv", "~/z/blog/public/files/hard-to-vary/key-v0.csv"),
        "htv_unseen_blind.csv": (STUDY_DIR / "inputs" / "htv_unseen_blind.csv", "inputs/htv_unseen_blind.csv"),
        "htv_unseen_key.csv": (STUDY_DIR / "inputs" / "htv_unseen_key.csv", "inputs/htv_unseen_key.csv"),
    }
    results: dict[str, Any] = {}
    all_ok = True
    for fname, (path, display_path) in targets.items():
        actual = sha256_file(path)
        exp = expected.get(fname)
        ok = exp is not None and actual == exp
        all_ok = all_ok and ok
        results[fname] = {
            "path": display_path,
            "expected_sha256": exp,
            "actual_sha256": actual,
            "match": ok,
        }
    return {"all_match": all_ok, "files": results}


def check_unseen_benchmark(
    v0_items: list[dict[str, str]],
    blind_rows: list[dict[str, str]],
    key_rows: list[dict[str, str]],
) -> dict[str, Any]:
    key_by_id = {r["id"]: r for r in key_rows}
    blind_by_id = {r["id"]: r for r in blind_rows}
    assert len(blind_rows) == 180 and len(key_rows) == 180
    assert set(blind_by_id) == set(key_by_id)

    wc_mismatches = 0
    arm_wcs: dict[str, list[int]] = defaultdict(list)
    phenom_wcs: dict[str, dict[str, int]] = defaultdict(dict)
    domain_phenoms: dict[str, set[str]] = defaultdict(set)

    for row in blind_rows:
        meta = key_by_id[row["id"]]
        wc = len(row["explanation"].split())
        if wc != int(meta["word_count"]):
            wc_mismatches += 1
        arm = meta["arm"]
        ph = meta["phenomenon_id"]
        arm_wcs[arm].append(wc)
        phenom_wcs[ph][arm] = wc
        domain_phenoms[meta["domain"]].add(ph)

    tight_plus3_le_easy = sum(
        1 for d in phenom_wcs.values() if d["tight_short"] + 3 <= d["easy_long"]
    )
    easy_plus3_le_stuffed = sum(
        1 for d in phenom_wcs.values() if d["easy_long"] + 3 <= d["specificity_stuffed"]
    )
    wc_acc_tight_gt_easy = sum(
        1 for d in phenom_wcs.values() if d["tight_short"] > d["easy_long"]
    ) / len(phenom_wcs)
    wc_acc_tight_gt_stuffed = sum(
        1 for d in phenom_wcs.values() if d["tight_short"] > d["specificity_stuffed"]
    ) / len(phenom_wcs)

    v0_ids = {r["id"] for r in v0_items}
    unseen_ids = {r["id"] for r in blind_rows}
    v0_norm = {r["phenomenon"].strip().lower() for r in v0_items} | {
        r["explanation"].strip().lower() for r in v0_items
    }
    unseen_norm = {r["phenomenon"].strip().lower() for r in blind_rows} | {
        r["explanation"].strip().lower() for r in blind_rows
    }

    def ngrams5(text: str) -> set[tuple[str, ...]]:
        words = re.findall(r"[a-z0-9]+", text.lower())
        return {tuple(words[i : i + 5]) for i in range(max(0, len(words) - 4))}

    v0_5g = set().union(*(ngrams5(r["phenomenon"] + " " + r["explanation"]) for r in v0_items))
    un_5g = set().union(*(ngrams5(r["phenomenon"] + " " + r["explanation"]) for r in blind_rows))

    return {
        "n_items": len(blind_rows),
        "n_phenomena": len(phenom_wcs),
        "domains": {dom: len(phs) for dom, phs in sorted(domain_phenoms.items())},
        "word_count_csv_mismatches": wc_mismatches,
        "arm_word_count_stats": {
            arm: {
                "min": int(min(arm_wcs[arm])),
                "max": int(max(arm_wcs[arm])),
                "mean": float(np.mean(arm_wcs[arm])),
            }
            for arm in ARMS
        },
        "tight_plus_3_le_easy_count": tight_plus3_le_easy,
        "easy_plus_3_le_stuffed_count": easy_plus3_le_stuffed,
        "word_count_baseline_acc_tight_gt_easy": float(wc_acc_tight_gt_easy),
        "word_count_baseline_acc_tight_gt_stuffed": float(wc_acc_tight_gt_stuffed),
        "overlap_with_v0": {
            "id_overlap": len(v0_ids & unseen_ids),
            "exact_normalized_text_overlap": len(v0_norm & unseen_norm),
            "word_5gram_overlap": len(v0_5g & un_5g),
        },
    }


def extract_surface_features(text: str, connector_re: re.Pattern[str]) -> list[float]:
    tokens = text.split()
    wc = len(tokens)
    mean_wl = float(np.mean([sum(ch.isalnum() for ch in tok) for tok in tokens])) if tokens else 0.0
    conn = len(connector_re.findall(text))
    punct = text.count(",") + text.count(";")
    return [float(wc), mean_wl, float(conn), float(punct)]


def run_lopo_4feat(X: np.ndarray, y: np.ndarray, groups: np.ndarray) -> tuple[float, int, list[dict[str, Any]], list[float]]:
    gkf = GroupKFold(n_splits=30)
    pair_hits = 0
    item_hits = 0
    missed_pairs: list[dict[str, Any]] = []
    diffs: list[float] = []
    for train_idx, test_idx in gkf.split(X, y, groups):
        pipe = Pipeline(
            [
                ("scaler", StandardScaler()),
                ("clf", LogisticRegression(C=1.0, max_iter=1000)),
            ]
        )
        pipe.fit(X[train_idx], y[train_idx])
        probs = pipe.predict_proba(X[test_idx])[:, 1]
        preds = (probs >= 0.5).astype(int)
        item_hits += int((preds == y[test_idx]).sum())
        b_pos = 0 if y[test_idx][0] == 1 else 1
        w_pos = 1 - b_pos
        pb, pw = float(probs[b_pos]), float(probs[w_pos])
        diffs.append(pb - pw)
        if pb > pw:
            pair_hits += 1
        else:
            missed_pairs.append(
                {"pair": int(groups[test_idx][0]), "p_better": pb, "p_worse": pw}
            )
    return pair_hits / 30.0, pair_hits, missed_pairs, [item_hits / len(y), float(np.mean(diffs))]


def part_a_audit(v0_items: list[dict[str, str]], v0_keys: list[dict[str, str]]) -> dict[str, Any]:
    key_by_id = {r["id"]: r for r in v0_keys}
    by_pair: dict[int, dict[str, dict[str, Any]]] = defaultdict(dict)
    rows: list[dict[str, Any]] = []
    for r in v0_items:
        k = key_by_id[r["id"]]
        entry = {
            "id": r["id"],
            "pair": int(k["pair"]),
            "side": k["side"],
            "origin": k["origin"],
            "phenomenon": r["phenomenon"],
            "explanation": r["explanation"],
            "word_count": len(r["explanation"].split()),
        }
        rows.append(entry)
        by_pair[entry["pair"]][entry["side"]] = entry

    wc_wins = wc_ties = wc_losses = 0
    reversed_pairs = []
    for pair_id in sorted(by_pair):
        b = by_pair[pair_id]["better"]
        w = by_pair[pair_id]["worse"]
        if b["word_count"] > w["word_count"]:
            wc_wins += 1
        elif b["word_count"] == w["word_count"]:
            wc_ties += 1
            reversed_pairs.append(pair_id)
        else:
            wc_losses += 1
            reversed_pairs.append(pair_id)

    y = np.array([1 if r["side"] == "better" else 0 for r in rows], dtype=int)
    groups = np.array([r["pair"] for r in rows], dtype=int)
    pair_indices = [np.where(groups == p)[0] for p in sorted(by_pair)]

    def eval_regex_variant(conn_re: re.Pattern[str]) -> dict[str, Any]:
        X = np.array(
            [extract_surface_features(r["explanation"], conn_re) for r in rows],
            dtype=float,
        )
        pair_acc, pair_hits, missed, extras = run_lopo_4feat(X, y, groups)
        sc_full = StandardScaler()
        clf_full = LogisticRegression(C=1.0, max_iter=1000).fit(sc_full.fit_transform(X), y)

        rng = np.random.default_rng(0)
        ge_count = 0
        perm_accs = []
        for _ in range(2000):
            y_perm = y.copy()
            flips = rng.integers(0, 2, size=len(pair_indices))
            for idx_pair, fl in zip(pair_indices, flips):
                if fl:
                    y_perm[idx_pair] = 1 - y_perm[idx_pair]
            p_acc, _, _, _ = run_lopo_4feat(X, y_perm, groups)
            perm_accs.append(p_acc)
            if p_acc >= pair_acc - 1e-12:
                ge_count += 1

        return {
            "pair_acc": float(pair_acc),
            "pair_hits": int(pair_hits),
            "n_pairs": 30,
            "item_acc": float(extras[0]),
            "mean_prob_diff": float(extras[1]),
            "missed_pairs": missed,
            "full_fit_standardized_coefs": {
                "word_count": float(clf_full.coef_[0][0]),
                "mean_word_len": float(clf_full.coef_[0][1]),
                "causal_connector_count": float(clf_full.coef_[0][2]),
                "comma_semicolon_count": float(clf_full.coef_[0][3]),
                "intercept": float(clf_full.intercept_[0]),
            },
            "permutation_test_2000_flips": {
                "n_draws": 2000,
                "seed": 0,
                "ge_count": int(ge_count),
                "p_value_raw": float(ge_count / 2000.0),
                "p_value_plus_one": float((ge_count + 1) / 2001.0),
                "null_mean_acc": float(np.mean(perm_accs)),
                "exact_binom_one_sided_p": float(binomtest(pair_hits, 30, 0.5, alternative="greater").pvalue),
            },
        }

    plan_res = eval_regex_variant(PLAN_CONNECTOR_RE)
    alt_res = eval_regex_variant(ALT_CONNECTOR_RE)

    # Descriptive (1,2)-gram TF-IDF LOPO baseline
    texts = [r["explanation"] for r in rows]
    gkf = GroupKFold(n_splits=30)
    tfidf_hits = 0
    for train_idx, test_idx in gkf.split(texts, y, groups):
        vec = TfidfVectorizer(ngram_range=(1, 2), min_df=2)
        Xtr = vec.fit_transform([texts[i] for i in train_idx])
        Xte = vec.transform([texts[i] for i in test_idx])
        clf = LogisticRegression(C=1.0, max_iter=1000).fit(Xtr, y[train_idx])
        probs = clf.predict_proba(Xte)[:, 1]
        b_pos = 0 if y[test_idx][0] == 1 else 1
        w_pos = 1 - b_pos
        if probs[b_pos] > probs[w_pos]:
            tfidf_hits += 1

    # H1 verdict strictly from PLAN.md
    p_val = plan_res["permutation_test_2000_flips"]["p_value_plus_one"]
    if plan_res["pair_hits"] >= 25 and p_val < 0.01:
        h1_verdict = "supported"
    elif plan_res["pair_hits"] <= 23:
        h1_verdict = "refuted"
    else:
        h1_verdict = "inconclusive"

    return {
        "n_items": len(rows),
        "n_pairs": 30,
        "word_count_stats": {
            "better_mean": float(np.mean([by_pair[p]["better"]["word_count"] for p in by_pair])),
            "worse_mean": float(np.mean([by_pair[p]["worse"]["word_count"] for p in by_pair])),
            "pair_acc": float(wc_wins / 30.0),
            "wins": wc_wins,
            "ties": wc_ties,
            "losses": wc_losses,
            "reversed_or_tied_pairs": reversed_pairs,
        },
        "surface_4feat_plan_regex": plan_res,
        "surface_4feat_prompt_regex_sensitivity": alt_res,
        "tfidf_1_2_gram_lopo": {
            "pair_hits": int(tfidf_hits),
            "n_pairs": 30,
            "pair_acc": float(tfidf_hits / 30.0),
        },
        "H1_verdict": h1_verdict,
    }


def krippendorff_alpha_ordinal(mat: np.ndarray) -> float:
    """Canonical Krippendorff (2011) ordinal alpha from PLAN.md."""
    coinc = np.zeros((5, 5), dtype=float)
    for row in mat:
        valid = [int(x) for x in row if x is not None]
        m_u = len(valid)
        if m_u < 2:
            continue
        inv = 1.0 / (m_u - 1)
        for i in range(m_u):
            for j in range(m_u):
                if i != j:
                    coinc[valid[i] - 1, valid[j] - 1] += inv
    n_c = coinc.sum(axis=1)
    n = float(n_c.sum())
    if n <= 1.0:
        return float("nan")
    delta2 = np.zeros((5, 5), dtype=float)
    for c in range(5):
        for k in range(5):
            if c == k:
                continue
            lo, hi = min(c, k), max(c, k)
            s = float(n_c[lo : hi + 1].sum()) - 0.5 * float(n_c[c] + n_c[k])
            delta2[c, k] = s * s
    d_o = float((coinc * delta2).sum()) / n
    d_e = float((np.outer(n_c, n_c) * delta2).sum()) / (n * (n - 1.0))
    if d_e == 0.0:
        return 1.0 if d_o == 0.0 else 0.0
    return float(1.0 - d_o / d_e)


def krippendorff_alpha_interval(mat: np.ndarray) -> float:
    """Quadratic/interval Krippendorff alpha reference check."""
    coinc = np.zeros((5, 5), dtype=float)
    for row in mat:
        valid = [int(x) for x in row if x is not None]
        m_u = len(valid)
        if m_u < 2:
            continue
        inv = 1.0 / (m_u - 1)
        for i in range(m_u):
            for j in range(m_u):
                if i != j:
                    coinc[valid[i] - 1, valid[j] - 1] += inv
    n_c = coinc.sum(axis=1)
    n = float(n_c.sum())
    if n <= 1.0:
        return float("nan")
    delta2 = np.array([[(c - k) ** 2 for k in range(5)] for c in range(5)], dtype=float)
    d_o = float((coinc * delta2).sum()) / n
    d_e = float((np.outer(n_c, n_c) * delta2).sum()) / (n * (n - 1.0))
    if d_e == 0.0:
        return 1.0 if d_o == 0.0 else 0.0
    return float(1.0 - d_o / d_e)


def gwet_ac2_quadratic(mat: np.ndarray) -> float:
    """Gwet's ordinal AC2 with quadratic weights from PLAN.md."""
    w = np.array([[1.0 - ((c - k) / 4.0) ** 2 for k in range(5)] for c in range(5)], dtype=float)
    pa_vals = []
    pi = np.zeros(5, dtype=float)
    valid_units = 0
    for row in mat:
        valid = [int(x) - 1 for x in row if x is not None]
        m_u = len(valid)
        if m_u < 2:
            continue
        valid_units += 1
        s_w = 0.0
        for i in range(m_u):
            pi[valid[i]] += 1.0 / m_u
            for j in range(m_u):
                if i != j:
                    s_w += w[valid[i], valid[j]]
        pa_vals.append(s_w / (m_u * (m_u - 1)))
    pa = float(np.mean(pa_vals))
    pi /= valid_units
    p_e = (float(w.sum()) / 20.0) * float((pi * (1.0 - pi)).sum())
    if 1.0 - p_e == 0.0:
        return 1.0
    return float((pa - p_e) / (1.0 - p_e))


def bootstrap_mean_ci(values: list[float] | np.ndarray, n_boot: int = 2000, seed: int = 0) -> tuple[float, float, float]:
    arr = np.asarray(values, dtype=float)
    rng = np.random.default_rng(seed)
    idx = rng.integers(0, len(arr), size=(n_boot, len(arr)))
    means = arr[idx].mean(axis=1)
    lo, hi = np.percentile(means, [2.5, 97.5])
    return float(arr.mean()), float(lo), float(hi)


def parse_score_from_raw(raw_response: str) -> tuple[int | None, str]:
    matches = SCORE_LINE_RE.findall(raw_response or "")
    if matches:
        return int(matches[-1]), "line"
    matches = SCORE_FALLBACK_RE.findall(raw_response or "")
    if matches:
        return int(matches[-1]), "fallback"
    return None, "unparsed"


def calibration_range_restriction_demo() -> dict[str, Any]:
    """Synthetic demonstration of within-half Krippendorff alpha collapse vs Gwet AC2."""
    rng = np.random.default_rng(0)
    alphas, ac2s, within1s, frac45s = [], [], [], []
    for _ in range(2000):
        z = rng.normal(4.35, 0.30, size=(30, 1))
        mat = np.clip(np.rint(z + rng.normal(0.0, 0.55, size=(30, 3))), 1, 5).astype(int)
        frac45s.append(float(np.mean((mat == 4) | (mat == 5))))
        w1 = np.mean([abs(int(mat[u, a]) - int(mat[u, b])) <= 1 for u in range(30) for a in range(3) for b in range(a + 1, 3)])
        within1s.append(float(w1))
        alphas.append(krippendorff_alpha_ordinal(mat))
        ac2s.append(gwet_ac2_quadratic(mat))
    return {
        "n_draws": 2000,
        "n_items": 30,
        "n_raters": 3,
        "mean_frac_in_4_5": float(np.mean(frac45s)),
        "mean_within_1": float(np.mean(within1s)),
        "mean_alpha_ord": float(np.mean(alphas)),
        "prob_alpha_lt_0_25": float(np.mean(np.asarray(alphas) < 0.25)),
        "mean_gwet_ac2": float(np.mean(ac2s)),
        "prob_ac2_ge_0_80": float(np.mean(np.asarray(ac2s) >= 0.80)),
    }


def part_b_audit(key_rows: list[dict[str, str]]) -> dict[str, Any]:
    key_by_id = {r["id"]: r for r in key_rows}
    phenoms = sorted({r["phenomenon_id"] for r in key_rows})
    expected_ids = set(key_by_id)

    parse_summary: dict[str, Any] = {}
    scores: dict[str, dict[str, dict[str, dict[str, int]]]] = {
        m: {p: defaultdict(dict) for p in PROTOCOLS} for m in MODELS
    }
    raw_by_cell: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)

    for model in MODELS:
        rollout_path = STUDY_DIR / "out" / f"rollouts_{model}.jsonl"
        rows = [json.loads(line) for line in rollout_path.read_text(encoding="utf-8").splitlines() if line.strip()]
        parse_summary[model] = {}
        for proto in PROTOCOLS:
            prows = [r for r in rows if r["protocol"] == proto]
            seen_ids = {r["id"] for r in prows}
            assert len(prows) == 180 and seen_ids == expected_ids, f"ID coverage mismatch for {model} {proto}"
            modes = Counter()
            stored_mismatches = 0
            score_dist = Counter()
            finish_dist = Counter()
            toks = []
            for r in prows:
                parsed, mode = parse_score_from_raw(r.get("raw_response", ""))
                modes[mode] += 1
                if parsed != r.get("score"):
                    stored_mismatches += 1
                score_dist[r.get("score")] += 1
                finish_dist[r.get("finish_reason")] += 1
                toks.append(int(r.get("completion_tokens", 0)))
                meta = key_by_id[r["id"]]
                scores[model][proto][meta["phenomenon_id"]][meta["arm"]] = int(parsed)
                raw_by_cell[(model, proto)].append(r)

            parse_summary[model][proto] = {
                "total": len(prows),
                "parsed_plan_line": int(modes["line"]),
                "parsed_plan_fallback": int(modes["fallback"]),
                "unparsed": int(modes["unparsed"]),
                "stored_score_mismatches": stored_mismatches,
                "finish_reason_counts": dict(finish_dist),
                "completion_tokens": {
                    "min": int(min(toks)),
                    "median": int(np.median(toks)),
                    "max": int(max(toks)),
                },
                "score_distribution": {str(k): int(score_dist.get(k, 0)) for k in [1, 2, 3, 4, 5]},
            }

    cells: dict[str, dict[str, Any]] = {}
    for proto in PROTOCOLS:
        cells[proto] = {}
        for model in MODELS:
            arm_means = {}
            arm_stds = {}
            for arm in ARMS:
                vals = [scores[model][proto][ph][arm] for ph in phenoms]
                arm_means[arm] = float(np.mean(vals))
                arm_stds[arm] = float(np.std(vals, ddof=1))

            opp_vals = np.array([scores[model][proto][ph]["opposite_compatible"] for ph in phenoms])
            opp_eq1 = float(np.mean(opp_vals == 1))
            opp_le2 = float(np.mean(opp_vals <= 2))

            pair_accs = {}
            for other in ["easy_long", "specificity_stuffed", "postulate_law", "opposite_compatible"]:
                hits = [1.0 if scores[model][proto][ph]["tight_short"] > scores[model][proto][ph][other] else 0.0 for ph in phenoms]
                wins = int(sum(1 for ph in phenoms if scores[model][proto][ph]["tight_short"] > scores[model][proto][ph][other]))
                ties = int(sum(1 for ph in phenoms if scores[model][proto][ph]["tight_short"] == scores[model][proto][ph][other]))
                losses = int(sum(1 for ph in phenoms if scores[model][proto][ph]["tight_short"] < scores[model][proto][ph][other]))
                mu, lo, hi = bootstrap_mean_ci(hits, n_boot=2000, seed=0)
                pair_accs[f"tight_short_gt_{other}"] = {
                    "acc": mu,
                    "ci95": [lo, hi],
                    "wins": wins,
                    "ties": ties,
                    "losses": losses,
                }

            inf_diffs = [scores[model][proto][ph]["specificity_stuffed"] - scores[model][proto][ph]["easy_long"] for ph in phenoms]
            inf_mu, inf_lo, inf_hi = bootstrap_mean_ci(inf_diffs, n_boot=2000, seed=0)
            drop_acc = pair_accs["tight_short_gt_easy_long"]["acc"] - pair_accs["tight_short_gt_specificity_stuffed"]["acc"]

            cells[proto][model] = {
                "arm_means": arm_means,
                "arm_stds": arm_stds,
                "opposite_compatible_rejection": {"eq_1": opp_eq1, "le_2": opp_le2},
                "pair_accuracies": pair_accs,
                "stuffing_inflation": {
                    "mean": inf_mu,
                    "ci95": [inf_lo, inf_hi],
                    "diff_counts": {str(k): int(v) for k, v in sorted(Counter(inf_diffs).items())},
                },
                "pair_acc_drop_from_stuffing": float(drop_acc),
                "pair_acc_drop_from_stuffing_pp": float(drop_acc * 100.0),
            }

    # Inter-model agreement per protocol
    agreement: dict[str, Any] = {}
    for proto in PROTOCOLS:
        mat_all = np.array([[scores[m][proto][ph][arm] for m in MODELS] for ph in phenoms for arm in ARMS], dtype=int)
        mat_anc_cluster = np.array([[[scores[m][proto][ph][arm] for m in MODELS] for arm in ANCHORED_ARMS] for ph in phenoms], dtype=int)
        mat_anc = mat_anc_cluster.reshape(-1, 3)
        mat_pos = np.array([[scores[m][proto][ph]["postulate_law"] for m in MODELS] for ph in phenoms], dtype=int)

        rng = np.random.default_rng(0)
        b_alpha, b_ac2 = [], []
        for _ in range(2000):
            idx = rng.integers(0, len(phenoms), size=len(phenoms))
            sub = mat_anc_cluster[idx].reshape(-1, 3)
            b_alpha.append(krippendorff_alpha_ordinal(sub))
            b_ac2.append(gwet_ac2_quadratic(sub))
        a_lo, a_hi = np.percentile(b_alpha, [2.5, 97.5])
        c_lo, c_hi = np.percentile(b_ac2, [2.5, 97.5])

        pairwise_anc = {}
        for i in range(len(MODELS)):
            for j in range(i + 1, len(MODELS)):
                m1, m2 = MODELS[i], MODELS[j]
                s1, s2 = mat_anc[:, i], mat_anc[:, j]
                rho, _ = spearmanr(s1, s2)
                pairwise_anc[f"{m1}_vs_{m2}"] = {
                    "exact": float(np.mean(s1 == s2)),
                    "within_1": float(np.mean(np.abs(s1 - s2) <= 1)),
                    "mad": float(np.mean(np.abs(s1 - s2))),
                    "mean_diff_m2_minus_m1": float(np.mean(s2 - s1)),
                    "spearman_rho": float(rho),
                }

        agreement[proto] = {
            "all_180": {
                "krippendorff_alpha_ordinal": krippendorff_alpha_ordinal(mat_all),
                "krippendorff_alpha_interval_ref": krippendorff_alpha_interval(mat_all),
                "gwet_ac2_quadratic": gwet_ac2_quadratic(mat_all),
            },
            "anchored_108": {
                "krippendorff_alpha_ordinal": krippendorff_alpha_ordinal(mat_anc),
                "krippendorff_alpha_ordinal_cluster_ci95": [float(a_lo), float(a_hi)],
                "krippendorff_alpha_interval_ref": krippendorff_alpha_interval(mat_anc),
                "gwet_ac2_quadratic": gwet_ac2_quadratic(mat_anc),
                "gwet_ac2_quadratic_cluster_ci95": [float(c_lo), float(c_hi)],
                "pairwise": pairwise_anc,
            },
            "postulate_law_36": {
                "krippendorff_alpha_ordinal": krippendorff_alpha_ordinal(mat_pos),
                "krippendorff_alpha_interval_ref": krippendorff_alpha_interval(mat_pos),
                "gwet_ac2_quadratic": gwet_ac2_quadratic(mat_pos),
            },
        }

    # Protocol contrasts: P_v0 -> P_counterfactual and P_naive -> P_v0
    contrasts_v0_to_cf: dict[str, Any] = {}
    contrasts_naive_to_v0: dict[str, Any] = {}
    for model in MODELS:
        inf_v0 = np.array([scores[model]["P_v0"][ph]["specificity_stuffed"] - scores[model]["P_v0"][ph]["easy_long"] for ph in phenoms], dtype=float)
        inf_cf = np.array([scores[model]["P_counterfactual"][ph]["specificity_stuffed"] - scores[model]["P_counterfactual"][ph]["easy_long"] for ph in phenoms], dtype=float)
        red_mu, red_lo, red_hi = bootstrap_mean_ci(inf_v0 - inf_cf, n_boot=2000, seed=0)

        st_v0 = np.array([1.0 if scores[model]["P_v0"][ph]["tight_short"] > scores[model]["P_v0"][ph]["specificity_stuffed"] else 0.0 for ph in phenoms])
        st_cf = np.array([1.0 if scores[model]["P_counterfactual"][ph]["tight_short"] > scores[model]["P_counterfactual"][ph]["specificity_stuffed"] else 0.0 for ph in phenoms])
        st_mu, st_lo, st_hi = bootstrap_mean_ci(st_cf - st_v0, n_boot=2000, seed=0)

        ez_v0 = np.array([1.0 if scores[model]["P_v0"][ph]["tight_short"] > scores[model]["P_v0"][ph]["easy_long"] else 0.0 for ph in phenoms])
        ez_cf = np.array([1.0 if scores[model]["P_counterfactual"][ph]["tight_short"] > scores[model]["P_counterfactual"][ph]["easy_long"] else 0.0 for ph in phenoms])
        ez_mu, ez_lo, ez_hi = bootstrap_mean_ci(ez_cf - ez_v0, n_boot=2000, seed=0)

        contrasts_v0_to_cf[model] = {
            "inflation_reduction_v0_minus_cf": {"mean": red_mu, "ci95": [red_lo, red_hi]},
            "tight_gt_stuffed_acc_gain": {"mean": st_mu, "mean_pp": st_mu * 100.0, "ci95_pp": [st_lo * 100.0, st_hi * 100.0]},
            "tight_gt_easy_acc_change": {"mean": ez_mu, "mean_pp": ez_mu * 100.0, "ci95_pp": [ez_lo * 100.0, ez_hi * 100.0]},
        }

        ez_nv = np.array([1.0 if scores[model]["P_naive"][ph]["tight_short"] > scores[model]["P_naive"][ph]["easy_long"] else 0.0 for ph in phenoms])
        nv_mu, nv_lo, nv_hi = bootstrap_mean_ci(ez_v0 - ez_nv, n_boot=2000, seed=0)
        contrasts_naive_to_v0[model] = {
            "tight_gt_easy_lift_v0_minus_naive_pp": {"mean_pp": nv_mu * 100.0, "ci95_pp": [nv_lo * 100.0, nv_hi * 100.0]},
            "opp_eq1_lift_pp": (cells["P_v0"][model]["opposite_compatible_rejection"]["eq_1"] - cells["P_naive"][model]["opposite_compatible_rejection"]["eq_1"]) * 100.0,
            "opp_le2_lift_pp": (cells["P_v0"][model]["opposite_compatible_rejection"]["le_2"] - cells["P_naive"][model]["opposite_compatible_rejection"]["le_2"]) * 100.0,
        }

    # Diagnostic rubric compliance audit on raw P_v0 and P_counterfactual responses
    compliance: dict[str, Any] = {}
    for model in MODELS:
        v0_none = sum(
            1
            for r in raw_by_cell[(model, "P_v0")]
            if str(r.get("variation") or "").strip().lower() in ("none", "none.", "n/a", "")
        )
        cf_tags = Counter()
        cf_contradictions = 0
        cf_opposite_tag_total = 0
        cf_opposite_on_tight = 0
        cf_extra_free_on_stuffed = 0
        for r in raw_by_cell[(model, "P_counterfactual")]:
            arm = key_by_id[r["id"]]["arm"]
            lines = [ln.strip() for ln in r["raw_response"].splitlines() if ln.strip()]
            core_line = next((ln for ln in lines if ln.lower().startswith("core swap:")), "")
            extra_line = next((ln for ln in lines if ln.lower().startswith("extra swap:")), "")
            cm = TAG_RE.findall(core_line)
            em = TAG_RE.findall(extra_line)
            ctag = cm[-1].upper() if cm else "MISSING"
            etag = em[-1].upper() if em else "MISSING"
            cf_tags[f"{ctag}|{etag}"] += 1
            if ctag == "OPPOSITE":
                cf_opposite_tag_total += 1
                if arm == "tight_short":
                    cf_opposite_on_tight += 1
            if arm == "specificity_stuffed" and etag == "FREE":
                cf_extra_free_on_stuffed += 1
            sc = int(r["score"])
            if (ctag == "BOUND" and etag in ("BOUND", "NONE") and sc in (1, 2, 3)) or (
                ctag == "FREE" and sc in (4, 5)
            ):
                cf_contradictions += 1

        compliance[model] = {
            "P_v0_variation_none_count": v0_none,
            "P_counterfactual_tag_pairs": dict(cf_tags),
            "P_counterfactual_core_opposite_total": cf_opposite_tag_total,
            "P_counterfactual_core_opposite_on_tight_short": cf_opposite_on_tight,
            "P_counterfactual_extra_free_on_stuffed": cf_extra_free_on_stuffed,
            "P_counterfactual_tag_vs_score_contradictions": cf_contradictions,
        }

    # Frozen H2, H3, H4 verdicts strictly from PLAN.md
    # H2
    n_ge_80 = sum(1 for m in MODELS if cells["P_v0"][m]["pair_accuracies"]["tight_short_gt_easy_long"]["acc"] >= 0.80)
    n_ge_75 = sum(1 for m in MODELS if cells["P_v0"][m]["pair_accuracies"]["tight_short_gt_easy_long"]["acc"] >= 0.75)
    anc_alpha_v0 = agreement["P_v0"]["anchored_108"]["krippendorff_alpha_ordinal"]
    if n_ge_80 >= 2 and anc_alpha_v0 >= 0.60:
        h2_verdict = "supported"
    elif n_ge_75 < 2 or anc_alpha_v0 < 0.50:
        h2_verdict = "refuted"
    else:
        h2_verdict = "inconclusive"

    # H3
    h3_sup_models = []
    h3_ref_models = []
    for m in MODELS:
        inf = cells["P_v0"][m]["stuffing_inflation"]
        drop_pp = cells["P_v0"][m]["pair_acc_drop_from_stuffing_pp"]
        if (inf["mean"] >= 0.30 and inf["ci95"][0] > 0.0) or drop_pp >= 15.0:
            h3_sup_models.append(m)
        if inf["mean"] < 0.10 and drop_pp < 8.0:
            h3_ref_models.append(m)
    if len(h3_sup_models) >= 2:
        h3_verdict = "supported"
    elif len(h3_ref_models) >= 2:
        h3_verdict = "refuted"
    else:
        h3_verdict = "inconclusive"

    # H4
    h4_sup_models = []
    h4_ref_models_a = []  # (red < 0.10 and gain < 5.0) or chg < -10.0
    h4_ref_models_b = []  # red < 0.10 and (gain < 5.0 or chg < -10.0)
    for m in MODELS:
        c = contrasts_v0_to_cf[m]
        red = c["inflation_reduction_v0_minus_cf"]
        gain_pp = c["tight_gt_stuffed_acc_gain"]["mean_pp"]
        chg_pp = c["tight_gt_easy_acc_change"]["mean_pp"]
        if (red["mean"] >= 0.30 and red["ci95"][0] > 0.0) or (gain_pp >= 10.0 and chg_pp >= -5.0):
            h4_sup_models.append(m)
        if (red["mean"] < 0.10 and gain_pp < 5.0) or chg_pp < -10.0:
            h4_ref_models_a.append(m)
        if red["mean"] < 0.10 and (gain_pp < 5.0 or chg_pp < -10.0):
            h4_ref_models_b.append(m)
    if len(h4_sup_models) >= 2:
        h4_verdict = "supported"
    elif len(h4_ref_models_b) >= 2:
        h4_verdict = "refuted"
    else:
        h4_verdict = "inconclusive"

    return {
        "parse_verification": parse_summary,
        "cells": cells,
        "agreement": agreement,
        "contrasts_v0_to_cf": contrasts_v0_to_cf,
        "contrasts_naive_to_v0": contrasts_naive_to_v0,
        "rubric_compliance_diagnostics": compliance,
        "verdicts": {
            "H2": {
                "verdict": h2_verdict,
                "n_models_ge_80pct": n_ge_80,
                "n_models_ge_75pct": n_ge_75,
                "anchored_108_alpha_ord": anc_alpha_v0,
            },
            "H3": {
                "verdict": h3_verdict,
                "supported_models": h3_sup_models,
                "refuted_models": h3_ref_models,
            },
            "H4": {
                "verdict": h4_verdict,
                "supported_models": h4_sup_models,
                "refuted_models_interp_a_or_drop": h4_ref_models_a,
                "refuted_models_interp_b_and_parenthesized": h4_ref_models_b,
                "audit_note": (
                    "Frozen H4 boolean rule triggers 'supported' on 2/3 models via two degenerate paths: "
                    "llama3-3b cuts stuffing inflation only by pushing easy_long (4.806) and opposite_compatible (5.000) "
                    "to ceiling while collapsing tight_short > easy_long by -41.7 pp (because PLAN.md omitted the -5.0 pp "
                    "guard on the inflation-reduction branch); mistral-7b raises tight > stuffed from 1/36 to 7/36 only "
                    "by breaking tie-collapse at 3 via 65% Score=1 [OPPOSITE] mislabeling, leaving stuffed > tight (19 vs 7). "
                    "Moreover, under unparenthesized precedence (red < 0.10 and gain < 5.0) or chg < -10.0, 2/3 models "
                    "(qwen3-4b, llama3-3b) simultaneously satisfy the refuted rule!"
                ),
            },
        },
    }


def main() -> None:
    hash_check = verify_inputs()
    assert hash_check["all_match"], f"Input SHA-256 mismatch: {hash_check}"

    with (BLOG_HTV_DIR / "items-v0.csv").open(encoding="utf-8") as f:
        v0_items = list(csv.DictReader(f))
    with (BLOG_HTV_DIR / "key-v0.csv").open(encoding="utf-8") as f:
        v0_keys = list(csv.DictReader(f))
    with (STUDY_DIR / "inputs" / "htv_unseen_blind.csv").open(encoding="utf-8") as f:
        blind_rows = list(csv.DictReader(f))
    with (STUDY_DIR / "inputs" / "htv_unseen_key.csv").open(encoding="utf-8") as f:
        key_rows = list(csv.DictReader(f))

    benchmark_check = check_unseen_benchmark(v0_items, blind_rows, key_rows)
    part_a = part_a_audit(v0_items, v0_keys)
    calibration_demo = calibration_range_restriction_demo()
    part_b = part_b_audit(key_rows)

    out = {
        "study_id": "20261123-hard-to-vary-pre-run-audit",
        "input_sha256_verification": hash_check,
        "benchmark_integrity_check": benchmark_check,
        "part_a": part_a,
        "calibration_range_restriction_demo": calibration_demo,
        "part_b": part_b,
        "frozen_verdicts_summary": {
            "H1": part_a["H1_verdict"],
            "H2": part_b["verdicts"]["H2"]["verdict"],
            "H3": part_b["verdicts"]["H3"]["verdict"],
            "H4": part_b["verdicts"]["H4"]["verdict"],
        },
    }

    out_path = Path(__file__).resolve().parent / "RECOMPUTED.json"
    out_path.write_text(json.dumps(out, indent=2) + "\n", encoding="utf-8")
    print(f"Wrote {out_path.relative_to(STUDY_DIR)}")
    print("Frozen verdicts:", json.dumps(out["frozen_verdicts_summary"]))


if __name__ == "__main__":
    main()
