#!/usr/bin/env python3
"""Part A: Zero-LLM methodological, surface-shortcut, and statistical-power audit of items-v0.csv.

Strictly reads items-v0.csv & key-v0.csv with ZERO LLM calls, leaving items-v0.csv
completely uncontaminated for the prospective post-Nov-29 run.
"""
from __future__ import annotations

import csv
import json
import re
import sys
from pathlib import Path

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupKFold
from sklearn.preprocessing import StandardScaler

sys.path.insert(0, str(Path(__file__).resolve().parent))
from ordinal_agreement_and_gaming import gwet_ac2_ordinal, krippendorff_ordinal_alpha

STUDY = Path(__file__).resolve().parent.parent
LOCAL_BLOG_V0 = STUDY.parent.parent / "files" / "hard-to-vary"
BLOG_V0 = LOCAL_BLOG_V0 if (LOCAL_BLOG_V0 / "items-v0.csv").exists() else (Path.home() / "z" / "blog" / "public" / "files" / "hard-to-vary")

CAUSAL_RE = re.compile(
    r"(,\s*so\b|\bbecause\b|\btherefore\b|\bso that\b|\buntil\b|\bwhereas\b)",
    re.I,
)


def extract_surface_features(text: str) -> list[float]:
    toks = text.split()
    wc = float(len(toks))
    clean_lens = [len(re.sub(r"[^A-Za-z0-9]", "", t)) for t in toks]
    mean_wl = float(np.mean(clean_lens)) if clean_lens else 0.0
    causal = float(len(CAUSAL_RE.findall(text)))
    punct = float(text.count(",") + text.count(";"))
    return [wc, mean_wl, causal, punct]


def lopo_pair_accuracy(
    X: np.ndarray | list[str],
    y: np.ndarray,
    groups: np.ndarray,
    is_tfidf: bool = False,
) -> tuple[float, list[dict]]:
    gkf = GroupKFold(n_splits=len(np.unique(groups)))
    probs = np.zeros(len(y), dtype=np.float64)
    for tr, te in gkf.split(np.zeros(len(y)), y, groups):
        if is_tfidf:
            vec = TfidfVectorizer(ngram_range=(1, 2), min_df=2)
            Xtr = vec.fit_transform([X[i] for i in tr])
            Xte = vec.transform([X[i] for i in te])
        else:
            sc = StandardScaler()
            Xtr = sc.fit_transform(X[tr])
            Xte = sc.transform(X[te])
        clf = LogisticRegression(C=1.0, max_iter=1000, random_state=0)
        clf.fit(Xtr, y[tr])
        probs[te] = clf.predict_proba(Xte)[:, 1]

    pair_details = []
    wins = 0
    ties = 0
    for g in sorted(np.unique(groups)):
        idx_b = [i for i in range(len(y)) if groups[i] == g and y[i] == 1][0]
        idx_w = [i for i in range(len(y)) if groups[i] == g and y[i] == 0][0]
        pb, pw = float(probs[idx_b]), float(probs[idx_w])
        win = pb > pw
        if pb == pw:
            ties += 1
        if win:
            wins += 1
        pair_details.append({"pair": int(g), "p_better": pb, "p_worse": pw, "win": bool(win)})
    return wins / len(pair_details), pair_details


def run_surface_audit() -> dict:
    items = {r["id"]: r for r in csv.DictReader(open(BLOG_V0 / "items-v0.csv", encoding="utf-8"))}
    keys = list(csv.DictReader(open(BLOG_V0 / "key-v0.csv", encoding="utf-8")))

    texts, y_list, groups, origins = [], [], [], []
    X_surf = []
    for k in keys:
        row = items[k["id"]]
        texts.append(row["explanation"])
        y_list.append(1 if k["side"] == "better" else 0)
        groups.append(int(k["pair"]))
        origins.append(k["origin"])
        X_surf.append(extract_surface_features(row["explanation"]))

    X_arr = np.asarray(X_surf, dtype=np.float64)
    y_arr = np.asarray(y_list, dtype=int)
    g_arr = np.asarray(groups, dtype=int)

    # 1. Raw word-count floor (baseline in v0 post)
    wc_wins = 0
    for g in range(1, 31):
        ib = [i for i in range(60) if g_arr[i] == g and y_arr[i] == 1][0]
        iw = [i for i in range(60) if g_arr[i] == g and y_arr[i] == 0][0]
        if X_arr[ib, 0] > X_arr[iw, 0]:
            wc_wins += 1

    # 2. 4-feature LOPO classifier
    acc4, details4 = lopo_pair_accuracy(X_arr, y_arr, g_arr, is_tfidf=False)

    # 3. 2,000-draw pair-label sign-flip permutation p-value (flipping better/worse labels per pair)
    rng = np.random.default_rng(0)
    pair_indices = {
        g: (
            [i for i in range(60) if g_arr[i] == g and y_arr[i] == 1][0],
            [i for i in range(60) if g_arr[i] == g and y_arr[i] == 0][0],
        )
        for g in range(1, 31)
    }
    perm_accs = []
    n_perm = 2000
    for _ in range(n_perm):
        y_perm = y_arr.copy()
        flips = rng.integers(0, 2, size=30)
        for p_idx, g in enumerate(range(1, 31)):
            if flips[p_idx] == 1:
                ib, iw = pair_indices[g]
                y_perm[ib], y_perm[iw] = y_perm[iw], y_perm[ib]
        pa, _ = lopo_pair_accuracy(X_arr, y_perm, g_arr, is_tfidf=False)
        perm_accs.append(pa)
    p_val_4 = float((np.asarray(perm_accs) >= acc4).mean())

    # 4. Descriptive TF-IDF (1,2)-gram LOPO check
    acc_tfidf, _ = lopo_pair_accuracy(texts, y_arr, g_arr, is_tfidf=True)

    # 5. Feature summary by side
    better_feats = X_arr[y_arr == 1]
    worse_feats = X_arr[y_arr == 0]
    feat_names = ["word_count", "mean_word_len", "causal_connector_count", "comma_semicolon_count"]
    feat_summary = {
        name: {
            "better_mean": float(better_feats[:, j].mean()),
            "worse_mean": float(worse_feats[:, j].mean()),
        }
        for j, name in enumerate(feat_names)
    }

    # Break down 4-feature misses by origin
    missed_pairs = [d["pair"] for d in details4 if not d["win"]]
    origin_by_pair = {int(k["pair"]): k["origin"] for k in keys if k["side"] == "worse"}
    miss_origins = {p: origin_by_pair[p] for p in missed_pairs}

    return {
        "word_count_wins": wc_wins,
        "word_count_acc": wc_wins / 30.0,
        "surface4_lopo_wins": int(round(acc4 * 30)),
        "surface4_lopo_acc": acc4,
        "surface4_perm_p": p_val_4,
        "surface4_perm_mean": float(np.mean(perm_accs)),
        "tfidf_lopo_wins": int(round(acc_tfidf * 30)),
        "tfidf_lopo_acc": acc_tfidf,
        "feature_means": feat_summary,
        "surface4_missed_pairs": miss_origins,
    }


def _fast_coinc_pair(rA: np.ndarray, rB: np.ndarray) -> np.ndarray:
    """For two raters over 30 pairs (shape 30 x 2), return per-pair 5x5 coincidence tensor (30, 5, 5)."""
    # rA, rB in {0,1,2,3,4} (representing scores 1..5), shape (30, 2)
    out = np.zeros((30, 5, 5), dtype=np.float64)
    p_idx = np.arange(30)
    for col in range(2):
        a = rA[:, col]
        b = rB[:, col]
        out[p_idx, a, b] += 1.0
        out[p_idx, b, a] += 1.0
    return out


def _batch_alpha_from_coinc(coinc_batch: np.ndarray) -> np.ndarray:
    """Vectorized Krippendorff ordinal alpha for B coincidence matrices (B, 5, 5)."""
    # coinc_batch: (B, 5, 5)
    marg = coinc_batch.sum(axis=2)  # (B, 5)
    n_tot = marg.sum(axis=1)  # (B,)
    cum = np.cumsum(marg, axis=1)  # (B, 5)
    # build delta2 (B, 5, 5)
    B = coinc_batch.shape[0]
    delta2 = np.zeros((B, 5, 5), dtype=np.float64)
    for i in range(5):
        for j in range(i + 1, 5):
            prev = cum[:, i - 1] if i > 0 else 0.0
            span = cum[:, j] - prev
            d = span - 0.5 * (marg[:, i] + marg[:, j])
            val = d * d
            delta2[:, i, j] = val
            delta2[:, j, i] = val
    d_o = (coinc_batch * delta2).sum(axis=(1, 2)) / np.maximum(n_tot, 1.0)
    exp_pairs = marg[:, :, None] * marg[:, None, :]
    denom = np.maximum(n_tot * (n_tot - 1.0), 1.0)
    d_e = (exp_pairs * delta2).sum(axis=(1, 2)) / denom
    alpha = np.where(d_e > 0.0, 1.0 - d_o / np.maximum(d_e, 1e-15), np.nan)
    return alpha


def run_power_and_range_audit(n_mc: int = 2000, n_boot: int = 1000) -> dict:
    """Monte Carlo power simulation of v0's N=30 pair thresholds + range restriction diagnostic.

    Generates latent true scores on 30 pairs (better ~ N(4.3, 0.55), worse ~ N(2.1, 0.85)),
    adds human and model Gaussian noise calibrated to target alpha levels, and tests
    rejection rates of v0's (model - human < -0.10 with 95% CI < 0) rule + within-half alpha.
    """
    rng = np.random.default_rng(0)

    def simulate_scenario(sigma_h: float, sigma_m: float, bias_m: float = 0.0) -> dict:
        # 3 humans + 1 model over 30 pairs x 2 sides
        gaps = []
        ci_rejections = []
        point_rejections = []
        hh_alphas = []
        mh_alphas = []
        within_b_alphas = []
        within_b_ac2s = []
        within_b_within1 = []

        # pre-draw bootstrap index tensor of shape (n_boot, 30)
        boot_idx = rng.integers(0, 30, size=(n_boot, 30))

        for _ in range(n_mc):
            z_b = rng.normal(4.35, 0.55, size=30)
            z_w = rng.normal(2.05, 0.85, size=30)
            z = np.stack([z_b, z_w], axis=1)  # (30, 2)

            h = []
            for _ in range(3):
                r = np.clip(np.rint(z + rng.normal(0.0, sigma_h, size=(30, 2))), 1, 5).astype(int) - 1
                h.append(r)
            m = np.clip(np.rint(z + bias_m + rng.normal(0.0, sigma_m, size=(30, 2))), 1, 5).astype(int) - 1

            # Per-pair coincidence tensors for 3 H-H pairs and 3 M-H pairs
            c_hh = (_fast_coinc_pair(h[0], h[1]) + _fast_coinc_pair(h[0], h[2]) + _fast_coinc_pair(h[1], h[2])) / 3.0
            c_mh = (_fast_coinc_pair(m, h[0]) + _fast_coinc_pair(m, h[1]) + _fast_coinc_pair(m, h[2])) / 3.0

            a_hh = float(_batch_alpha_from_coinc(c_hh.sum(axis=0, keepdims=True))[0])
            a_mh = float(_batch_alpha_from_coinc(c_mh.sum(axis=0, keepdims=True))[0])
            gap = a_mh - a_hh
            hh_alphas.append(a_hh)
            mh_alphas.append(a_mh)
            gaps.append(gap)
            point_rejections.append(gap < -0.10)

            # Fast vectorized bootstrap of gap over 30 pairs
            b_hh = c_hh[boot_idx].sum(axis=1)  # (n_boot, 5, 5)
            b_mh = c_mh[boot_idx].sum(axis=1)
            ba_hh = _batch_alpha_from_coinc(b_hh)
            ba_mh = _batch_alpha_from_coinc(b_mh)
            b_gap = ba_mh - ba_hh
            ci_hi = float(np.nanpercentile(b_gap, 97.5))
            ci_rejections.append(bool(gap < -0.10 and ci_hi < 0.0))

            # Within-better-half diagnostics across 3 humans
            wb_mat = [(x[:, 0] + 1).tolist() for x in h]
            wb_alpha = krippendorff_ordinal_alpha(wb_mat)
            wb_gwet = gwet_ac2_ordinal(wb_mat)
            within_b_alphas.append(wb_alpha)
            within_b_ac2s.append(wb_gwet["ac2"])
            within_b_within1.append(wb_gwet["within1"])

        return {
            "mean_alpha_HH": float(np.nanmean(hh_alphas)),
            "mean_alpha_MH": float(np.nanmean(mh_alphas)),
            "mean_gap": float(np.nanmean(gaps)),
            "power_point_gap_lt_neg010": float(np.mean(point_rejections)),
            "power_ci95_lt_0_and_gap_lt_neg010": float(np.mean(ci_rejections)),
            "within_better_mean_alpha": float(np.nanmean(within_b_alphas)),
            "within_better_p_alpha_lt_025": float(np.mean(np.asarray(within_b_alphas) < 0.25)),
            "within_better_mean_gwet_ac2": float(np.nanmean(within_b_ac2s)),
            "within_better_mean_within1": float(np.nanmean(within_b_within1)),
        }

    scenarios = {
        "null_same_noise_high_H": simulate_scenario(sigma_h=0.55, sigma_m=0.55),
        "mild_drop_sigma085": simulate_scenario(sigma_h=0.55, sigma_m=0.85),
        "mod_drop_sigma110": simulate_scenario(sigma_h=0.55, sigma_m=1.10),
        "severe_drop_sigma150": simulate_scenario(sigma_h=0.55, sigma_m=1.50),
        "bias_plus_noise": simulate_scenario(sigma_h=0.55, sigma_m=1.10, bias_m=0.5),
    }

    # Explicit check of vectorized coincidence formula vs canonical function
    test_h0 = rng.integers(1, 6, size=(30, 2)) - 1
    test_h1 = rng.integers(1, 6, size=(30, 2)) - 1
    c_pair = _fast_coinc_pair(test_h0, test_h1).sum(axis=0, keepdims=True)
    v_alpha = float(_batch_alpha_from_coinc(c_pair)[0])
    c_alpha = krippendorff_ordinal_alpha([
        (test_h0.reshape(-1) + 1).tolist(),
        (test_h1.reshape(-1) + 1).tolist(),
    ])
    assert abs(v_alpha - c_alpha) < 1e-12, (v_alpha, c_alpha)

    return {"n_mc": n_mc, "n_boot": n_boot, "scenarios": scenarios}


def run_item_rubric_audit() -> dict:
    """Deterministic item-structure findings on items-v0.csv & key-v0.csv."""
    items = {r["id"]: r for r in csv.DictReader(open(BLOG_V0 / "items-v0.csv", encoding="utf-8"))}
    keys = list(csv.DictReader(open(BLOG_V0 / "key-v0.csv", encoding="utf-8")))

    pairs = {}
    for k in keys:
        pairs.setdefault(int(k["pair"]), {})[k["side"]] = {
            **items[k["id"]],
            "origin": k["origin"],
        }

    # Check shared explicit numerical constraints across paired items (e.g., 10 metres in Pair 11)
    num_re = re.compile(r"\b\d+(?:\.\d+)?\b")
    shared_numbers = []
    for p, sides in sorted(pairs.items()):
        nb = set(num_re.findall(sides["better"]["explanation"]))
        nw = set(num_re.findall(sides["worse"]["explanation"]))
        if nb & nw:
            shared_numbers.append({"pair": p, "phenomenon": sides["better"]["phenomenon"], "shared_nums": sorted(nb & nw)})

    origin_counts = {}
    for p, sides in pairs.items():
        orig = sides["worse"]["origin"]
        origin_counts[orig] = origin_counts.get(orig, 0) + 1

    return {
        "n_pairs": len(pairs),
        "origin_counts": origin_counts,
        "shared_number_pairs": shared_numbers,
        "qualitative_rubric_findings": [
            "Anchor 1 ('explains opposite observation') is orthogonal to Anchors 2-5 ('number/centrality of free details'): an item with 1 free central detail can simultaneously fail Anchor 1, forcing raters to pick between non-monotone properties.",
            "Anchor 2 ('contains a clause that does nothing except match a known fact') detects post-hoc accommodation rather than free variation, overlapping unevenly with Anchor 3 ('one central detail is free') on historical ad-hoc patches (e.g. Pair 10 E60 power 2.00000016).",
            "Pair 9 (Uranus: unseen outer planet vs inverse-square drift) and Pair 8 (speed of light: invariance postulate vs Lorentz contraction) test textbook physical truth/postulates where an educated rater cannot avoid factual/postulate prior knowledge as instructed ('score how it is built, not whether it is true').",
            "Word-count alone gets 23/30 (76.7%); 4 deterministic surface features reach a substantially higher LOPO floor without reading meaning or applying the rubric.",
            "Human raters see both explanations of each phenomenon on one sheet (contrastive pair reading) while LLM raters see 1 item per prompt (unpaired absolute reading), confounding human-vs-model agreement gaps with presentation context.",
        ],
    }


def main() -> None:
    out_dir = STUDY / "out"
    out_dir.mkdir(parents=True, exist_ok=True)
    res = {
        "surface_audit": run_surface_audit(),
        "power_and_range_audit": run_power_and_range_audit(n_mc=2000, n_boot=1000),
        "item_rubric_audit": run_item_rubric_audit(),
    }
    out_path = out_dir / "partA_v0_audit.json"
    out_path.write_text(json.dumps(res, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(res, indent=2))


if __name__ == "__main__":
    main()
