#!/usr/bin/env python3
"""judge_diagnostics.py: Reusable diagnostics for LLM judges and reward models (stdlib + numpy only).

Covers four failure modes documented across prior judge-reliability audits (#57, B1/B2, papers/judge-scores):
  1. Operating-point mismatch (`operating_point_audit`): pooled AUROC vs within-prompt AUROC, fixed-budget
     error-review precision (`prec_err@b`), and exact expected Best-of-N selection accuracy, with paired
     prompt-cluster bootstrap CIs.
  2. Lincoln-Petersen overlap-recall inflation (`lp_overlap_audit`, `fit_lp_lift_alpha`): exact conditional
     covariance identity `gap = R_union * Cov(1_A, 1_B | correct) / (p_A * p_B)`, unlabeled pass-lift
     predictor `Lambda_unlab = P(A & B) / q^2`, and an unlabeled-lift-adjusted capture-recapture estimator
     usable when only passed items `A | B` are labeled.
  3. Provenance scaffolding & rationale-calibration decoupling (`scaffolding_score`, `scaffolding_asymmetry`,
     `rationale_decoupling_audit`): detects human-vs-LLM surface-scaffolding benchmark confounds (e.g. RB1
     math-prm) and measures ranking improvement vs Yes/No acceptance collapse when derivations are stripped.
  4. Cancellation-safe poolwise centering (`safe_pool_center`, `poolwise_u_alpha`): prevents catastrophic
     binary64 mean-subtraction tie corruption (`(r - r_max) + sum_k v_k (r_max - r_k)`).

CLI usage:
  python3 scout/checks/judge_diagnostics.py selftest
  python3 scout/checks/judge_diagnostics.py audit-csv <csv_path> --score-col score --gold-col gold_correct --prompt-col prompt_id

Author: Gemini 4 Carbon (High), 2026-11-23 (tracker #57, #77).
"""
from __future__ import annotations

import argparse
import csv
import json
import math
import re
import sys
from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple

import numpy as np


# ---------------------------------------------------------------------------
# Shared rank, AUROC, and paired prompt-cluster bootstrap helpers
# ---------------------------------------------------------------------------

def avg_ranks(s: np.ndarray) -> np.ndarray:
    """1-based average ranks on ties."""
    s = np.asarray(s, dtype=np.float64)
    u, inv, cnt = np.unique(s, return_inverse=True, return_counts=True)
    start = np.cumsum(cnt) - cnt
    return (start + (cnt + 1) / 2.0)[inv]


def auroc_tied(scores: Sequence[float], gold_correct: Sequence[int]) -> float:
    """P(score_correct > score_incorrect) + 0.5 * P(tie)."""
    s = np.asarray(scores, dtype=np.float64)
    o = np.asarray(gold_correct, dtype=np.int64)
    n1 = int((o == 1).sum())
    n0 = int((o == 0).sum())
    if n1 == 0 or n0 == 0:
        return float("nan")
    r = avg_ranks(s)
    return float((r[o == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0))


def within_prompt_auroc(
    scores: Sequence[float],
    gold_correct: Sequence[int],
    prompt_ids: Sequence,
) -> float:
    """Mean within-prompt pairwise concordance across prompts that have both correct and incorrect items."""
    s = np.asarray(scores, dtype=np.float64)
    o = np.asarray(gold_correct, dtype=np.int64)
    pids = np.asarray(prompt_ids)
    _, inv = np.unique(pids, return_inverse=True)
    order = np.argsort(inv, kind="mergesort")
    cnt = np.bincount(inv)
    starts = np.cumsum(cnt) - cnt
    vals = []
    for g in range(len(cnt)):
        ix = order[starts[g]:starts[g] + cnt[g]]
        og = o[ix]
        if (og == 1).any() and (og == 0).any():
            vals.append(auroc_tied(s[ix], og))
    return float(np.mean(vals)) if vals else float("nan")


class PromptClusterBoot:
    """Paired prompt-cluster bootstrap reusing identical cluster draws across contrasted statistics."""

    def __init__(self, prompt_ids: Sequence, n_boot: int = 1000, seed: int = 0):
        rng = np.random.default_rng(seed)
        ug, inv = np.unique(np.asarray(prompt_ids), return_inverse=True)
        order = np.argsort(inv, kind="mergesort")
        cnt = np.bincount(inv)
        starts = np.cumsum(cnt) - cnt
        self.n_clusters = len(ug)
        self.idx = []
        for _ in range(n_boot):
            pick = rng.integers(0, len(ug), len(ug))
            self.idx.append(np.concatenate([order[starts[p]:starts[p] + cnt[p]] for p in pick]))

    def ci(self, fn: Callable[[np.ndarray], float]) -> Tuple[float, float]:
        vals = np.array([fn(ix) for ix in self.idx], dtype=np.float64)
        if np.all(np.isnan(vals)):
            return float("nan"), float("nan")
        lo, hi = np.nanpercentile(vals, [2.5, 97.5])
        return float(lo), float(hi)


# ---------------------------------------------------------------------------
# 1. Fixed-budget error precision & exact Best-of-N selection accuracy
# ---------------------------------------------------------------------------

def prec_err_at_budget(scores: Sequence[float], gold_correct: Sequence[int], budget: float = 0.05) -> Dict[str, float]:
    """Audit lowest-scored fraction `budget`; tied boundary split proportionally in expectation."""
    s = np.asarray(scores, dtype=np.float64)
    o = np.asarray(gold_correct, dtype=np.int64)
    n = len(s)
    assert 0.0 < budget <= 1.0 and n > 0
    k = budget * n
    err_rate = float((o == 0).mean())
    u, inv = np.unique(s, return_inverse=True)
    tot = np.bincount(inv, minlength=len(u))
    bad = np.bincount(inv, weights=(o == 0).astype(np.float64), minlength=len(u))
    ct = np.cumsum(tot)
    prev = ct - tot
    take = np.clip(k - prev, 0.0, tot)
    caught = float((bad * take / np.maximum(tot, 1)).sum())
    n_err = int((o == 0).sum())
    prec = caught / k
    rec = caught / n_err if n_err > 0 else float("nan")
    return {
        "budget": float(budget),
        "prec_err": float(prec),
        "random_err": err_rate,
        "prec_minus_random": float(prec - err_rate),
        "recall_err": float(rec),
    }


def exact_best_of_n_correctness(
    scores: Sequence[float],
    gold_correct: Sequence[int],
    prompt_ids: Sequence,
    n_draws: int = 32,
    weights: Optional[Sequence[float]] = None,
) -> float:
    """Exact expected correctness of argmax over `n_draws` i.i.d. candidate draws per prompt (ties split proportionally)."""
    s = np.asarray(scores, dtype=np.float64)
    o = np.asarray(gold_correct, dtype=np.float64)
    pids = np.asarray(prompt_ids)
    w = np.ones(len(s), dtype=np.float64) if weights is None else np.asarray(weights, dtype=np.float64)
    _, inv = np.unique(pids, return_inverse=True)
    order = np.argsort(inv, kind="mergesort")
    cnt = np.bincount(inv)
    starts = np.cumsum(cnt) - cnt
    prompt_vals = []
    for g in range(len(cnt)):
        ix = order[starts[g]:starts[g] + cnt[g]]
        sg = s[ix]
        og = o[ix]
        pg = w[ix] / float(w[ix].sum())
        u, u_inv = np.unique(sg, return_inverse=True)
        q_lvl = np.bincount(u_inv, weights=pg, minlength=len(u))
        y_lvl = np.bincount(u_inv, weights=pg * og, minlength=len(u))
        H = np.cumsum(q_lvl)
        H_prev = H - q_lvl
        # Selection mass per tied level: H(t)^N - H(t^-)^N
        win_lvl = np.power(H, n_draws) - np.power(H_prev, n_draws)
        # Expected correctness in level is y_lvl / q_lvl
        nz = q_lvl > 0
        prompt_vals.append(float(np.sum(win_lvl[nz] * (y_lvl[nz] / q_lvl[nz]))))
    return float(np.mean(prompt_vals)) if prompt_vals else float("nan")


# ---------------------------------------------------------------------------
# 2. Lincoln-Petersen overlap-recall inflation & unlabeled-lift correction
# ---------------------------------------------------------------------------

def lp_overlap_audit(
    scores_a: Sequence[float],
    scores_b: Sequence[float],
    gold_correct: Sequence[int],
    q: float = 0.2,
    alpha_lift: float = 0.0,
) -> Dict[str, float]:
    """Compute Lincoln-Petersen union recall, exact conditional-covariance gap decomposition,
    unlabeled pass-overlap lift `Lambda_unlab`, and lift-adjusted union recall.

    Note: `lp_union_recall` and `adj_union_recall` inspect `gold_correct` ONLY on `A | B` (passed items),
    so they are deployable without labeling unpassed items. When full `gold_correct` is supplied,
    `true_union_recall` and the exact algebraic identity `gap == true_union_recall * psi_cond` are verified.
    """
    sa = np.asarray(scores_a, dtype=np.float64)
    sb = np.asarray(scores_b, dtype=np.float64)
    o = np.asarray(gold_correct, dtype=np.int64)
    n = len(sa)
    assert len(sb) == n and len(o) == n and n > 0
    k = int(round(q * n))
    q_eff = k / float(n)

    A = np.zeros(n, dtype=bool)
    B = np.zeros(n, dtype=bool)
    A[np.argsort(-sa, kind="mergesort")[:k]] = True
    B[np.argsort(-sb, kind="mergesort")[:k]] = True

    # Unlabeled pass-overlap lift (observable on all n items with zero human labels)
    unlab_both = float((A & B).mean())
    lambda_unlab = unlab_both / (q_eff * q_eff) if q_eff > 0 else float("nan")

    # Labeled quantities inside A | B
    c = (o == 1)
    fa = int((A & c).sum())
    fb = int((B & c).sum())
    m = int((A & B & c).sum())
    un = int(((A | B) & c).sum())

    if fa == 0 or fb == 0 or m == 0:
        lp_n_hat = float("nan")
        lp_rec = float("nan")
        adj_rec = float("nan")
    else:
        lp_n_hat = (fa * fb) / float(m)
        lp_rec = un / lp_n_hat
        # Unlabeled-lift adjustment: N_adj = N_LP * max(0.25, 1 + alpha_lift * (lambda_unlab - 1))
        # When two judges positively co-pass (lambda_unlab > 1), N_LP underestimates N_c, so scaling N_LP up lowers recall overstatement.
        scale = max(0.25, 1.0 + alpha_lift * (lambda_unlab - 1.0))
        adj_rec = min(1.0, un / (lp_n_hat * scale))

    tot_c = int(c.sum())
    true_rec = un / float(tot_c) if tot_c > 0 else float("nan")
    gap = lp_rec - true_rec if (not math.isnan(lp_rec) and not math.isnan(true_rec)) else float("nan")
    adj_gap = adj_rec - true_rec if (not math.isnan(adj_rec) and not math.isnan(true_rec)) else float("nan")

    # Exact conditional covariance decomposition: psi_cond = (p_AB / (p_A * p_B)) - 1
    if tot_c > 0 and fa > 0 and fb > 0:
        pA = fa / float(tot_c)
        pB = fb / float(tot_c)
        pAB = m / float(tot_c)
        cov_cond = pAB - pA * pB
        psi_cond = cov_cond / (pA * pB)
        identity_err = abs(gap - true_rec * psi_cond) if not math.isnan(gap) else 0.0
    else:
        cov_cond = float("nan")
        psi_cond = float("nan")
        identity_err = float("nan")

    return {
        "q": float(q),
        "n": n,
        "fa": fa,
        "fb": fb,
        "m": m,
        "un": un,
        "tot_correct": tot_c,
        "lambda_unlab": float(lambda_unlab),
        "lp_union_recall": float(lp_rec),
        "adj_union_recall": float(adj_rec),
        "true_union_recall": float(true_rec),
        "lp_gap": float(gap),
        "adj_gap": float(adj_gap),
        "cov_cond_correct": float(cov_cond),
        "psi_cond_correct": float(psi_cond),
        "identity_abs_err": float(identity_err),
    }


def fit_lp_lift_alpha(pair_records: Sequence[Dict[str, float]]) -> float:
    """Fit 1-parameter `alpha` mapping unlabeled excess lift `(lambda_unlab - 1)` to conditional excess lift
    `psi_cond_correct = (lp_union_recall / true_union_recall) - 1` via origin-constrained least squares."""
    xs, ys = [], []
    for r in pair_records:
        lu = r.get("lambda_unlab", float("nan"))
        tr = r.get("true_union_recall", float("nan"))
        lp = r.get("lp_union_recall", float("nan"))
        if math.isfinite(lu) and math.isfinite(tr) and math.isfinite(lp) and tr > 0:
            xs.append(lu - 1.0)
            ys.append((lp / tr) - 1.0)
    x = np.asarray(xs, dtype=np.float64)
    y = np.asarray(ys, dtype=np.float64)
    denom = float((x * x).sum())
    return float((x * y).sum() / denom) if denom > 1e-12 else 0.0


# ---------------------------------------------------------------------------
# 3. Surface-scaffolding asymmetry & rationale-calibration decoupling
# ---------------------------------------------------------------------------

_STEP_RE = re.compile(r"(?m)(?:^\s*(?:#{1,4}\s+|\*\*Step\b|Step\s+\d+|-\s+|\d+\.\s+))")
_CONNECTOR_RE = re.compile(r"\b(?:Therefore|Thus|Hence|Let's|First,|Second,|Finally,|To find|We can)\b", re.I)
_BOX_RE = re.compile(r"\\(?:boxed|fbox)\s*\{")


def scaffolding_score(text: str) -> float:
    """Parameter-free pedagogical/LLM-scaffolding density score per response.
    Counts structural markers (markdown/step headers, bulleted/numbered steps, pedagogical connectors,
    and explicit boxed-answer summaries) normalized by `log2(16 + word_count)` so sheer length alone
    cannot dominate structural formatting."""
    words = len(text.split())
    n_steps = len(_STEP_RE.findall(text))
    n_conn = len(_CONNECTOR_RE.findall(text))
    n_box = 1 if _BOX_RE.search(text) else 0
    return float((1.5 * n_steps + 1.0 * n_conn + 1.5 * n_box) / math.log2(16.0 + words))


def scaffolding_asymmetry(chosen_texts: Sequence[str], rejected_texts: Sequence[str]) -> Dict[str, object]:
    """Measure chosen-minus-rejected scaffolding asymmetry across paired benchmark items."""
    assert len(chosen_texts) == len(rejected_texts) and len(chosen_texts) > 0
    sc_c = np.array([scaffolding_score(t) for t in chosen_texts], dtype=np.float64)
    sc_r = np.array([scaffolding_score(t) for t in rejected_texts], dtype=np.float64)
    len_c = np.array([len(t) for t in chosen_texts], dtype=np.float64)
    len_r = np.array([len(t) for t in rejected_texts], dtype=np.float64)
    delta = sc_c - sc_r
    return {
        "n_pairs": len(chosen_texts),
        "mean_chosen_scaff": float(sc_c.mean()),
        "mean_rejected_scaff": float(sc_r.mean()),
        "mean_delta_scaff": float(delta.mean()),
        "median_delta_scaff": float(np.median(delta)),
        "frac_rejected_more_scaffolded": float((delta < 0).mean()),
        "mean_chosen_chars": float(len_c.mean()),
        "mean_rejected_chars": float(len_r.mean()),
        "per_pair_delta": delta.tolist(),
    }


def rationale_decoupling_audit(
    chosen_full_p_yes: Sequence[float],
    rejected_full_p_yes: Sequence[float],
    chosen_bare_p_yes: Sequence[float],
    rejected_bare_p_yes: Sequence[float],
    threshold: float = 0.5,
) -> Dict[str, float]:
    """Quantify ranking-vs-acceptance decoupling when rationales are stripped from paired evaluations."""
    cf = np.asarray(chosen_full_p_yes, dtype=np.float64)
    rf = np.asarray(rejected_full_p_yes, dtype=np.float64)
    cb = np.asarray(chosen_bare_p_yes, dtype=np.float64)
    rb = np.asarray(rejected_bare_p_yes, dtype=np.float64)
    n = len(cf)
    assert len(rf) == n and len(cb) == n and len(rb) == n and n > 0

    win_full = float(np.mean((cf > rf) + 0.5 * (cf == rf)))
    win_bare = float(np.mean((cb > rb) + 0.5 * (cb == rb)))

    acc_full = 0.5 * float((cf >= threshold).mean() + (rf < threshold).mean())
    acc_bare = 0.5 * float((cb >= threshold).mean() + (rb < threshold).mean())
    bare_correct_reject_rate = float((cb < threshold).mean())

    return {
        "n_pairs": n,
        "pair_win_full": win_full,
        "pair_win_bare": win_bare,
        "delta_pair_win_strip": float(win_bare - win_full),
        "yn_acc_full": acc_full,
        "yn_acc_bare": acc_bare,
        "delta_yn_acc_strip": float(acc_bare - acc_full),
        "bare_correct_reject_rate": bare_correct_reject_rate,
        "decoupled": bool((win_bare > win_full) and (acc_bare < acc_full)),
    }


# ---------------------------------------------------------------------------
# 4. Cancellation-safe poolwise centering & U_alpha (papers/judge-scores Proposition 1)
# ---------------------------------------------------------------------------

def safe_pool_center(scores: Sequence[float], weights: Sequence[float]) -> np.ndarray:
    """Cancellation-safe centering `(r_j - r_max) + sum_k v_k * (r_max - r_k)` for normalized weights `v`."""
    r = np.asarray(scores, dtype=np.float64)
    v = np.asarray(weights, dtype=np.float64)
    v = v / float(v.sum())
    r_max = float(np.max(r))
    shift = float(np.sum(v * (r_max - r)))
    return (r - r_max) + shift


def naive_pool_center(scores: Sequence[float], weights: Sequence[float]) -> np.ndarray:
    """Naive binary64 `r_j - sum_k v_k * r_k` (vulnerable to catastrophic cancellation near 1 - 2^-53)."""
    r = np.asarray(scores, dtype=np.float64)
    v = np.asarray(weights, dtype=np.float64)
    v = v / float(v.sum())
    mean = float(np.sum(v * r))
    return r - mean


def poolwise_u_alpha(
    per_question_residuals: Sequence[Sequence[float]],
    per_question_weights: Sequence[Sequence[float]],
    per_question_correct: Sequence[Sequence[int]],
    alpha: float = 0.3,
) -> float:
    """Pool candidate masses `v_{ij} / I` across `I` questions and compute top-`alpha` correctness `U_alpha`
    with proportional tie-block inclusion (eq. 2 of papers/judge-scores/paper.tex)."""
    I = len(per_question_residuals)
    assert I > 0 and 0.0 < alpha <= 1.0
    res_list, mass_list, cor_list = [], [], []
    for r_q, w_q, y_q in zip(per_question_residuals, per_question_weights, per_question_correct):
        rq = np.asarray(r_q, dtype=np.float64)
        wq = np.asarray(w_q, dtype=np.float64)
        yq = np.asarray(y_q, dtype=np.float64)
        wq = (wq / float(wq.sum())) / float(I)
        res_list.append(rq)
        mass_list.append(wq)
        cor_list.append(yq)
    r_all = np.concatenate(res_list)
    m_all = np.concatenate(mass_list)
    y_all = np.concatenate(cor_list)

    # Sort descending by residual, grouping exact floating-point ties
    u_desc = -np.unique(-r_all)
    tot_mass = np.zeros(len(u_desc), dtype=np.float64)
    cor_mass = np.zeros(len(u_desc), dtype=np.float64)
    # Map each item to its descending tie level
    u_asc, inv_asc = np.unique(r_all, return_inverse=True)
    # Reverse order so index 0 is highest score
    tot_asc = np.bincount(inv_asc, weights=m_all, minlength=len(u_asc))
    cor_asc = np.bincount(inv_asc, weights=m_all * y_all, minlength=len(u_asc))
    tot_mass = tot_asc[::-1]
    cor_mass = cor_asc[::-1]

    cum = np.cumsum(tot_mass)
    prev = cum - tot_mass
    take = np.clip(alpha - prev, 0.0, tot_mass)
    nz = tot_mass > 0
    retained_correct = float(np.sum(cor_mass[nz] * (take[nz] / tot_mass[nz])))
    return retained_correct / alpha


def selftest() -> Dict[str, object]:
    """Run deterministic self-checks including Proposition 1 of papers/judge-scores/paper.tex."""
    q = 2.0 ** -256
    w1 = [q, 1.0 - q]
    r1 = [0.0, 1.0]
    y1 = [0, 1]
    w2 = [0.5, 0.5]
    r2 = [0.0, 0.0]
    y2 = [0, 0]

    u_safe = poolwise_u_alpha([safe_pool_center(r1, w1), safe_pool_center(r2, w2)], [w1, w2], [y1, y2], alpha=0.3)
    u_naive = poolwise_u_alpha([naive_pool_center(r1, w1), naive_pool_center(r2, w2)], [w1, w2], [y1, y2], alpha=0.3)
    assert abs(u_safe - 1.0) < 1e-12, u_safe
    assert abs(u_naive - 0.5) < 1e-12, u_naive

    # Check exact algebraic LP covariance identity
    rng = np.random.default_rng(42)
    o = rng.integers(0, 2, size=500)
    sa = o * 0.5 + rng.normal(size=500)
    sb = sa * 0.7 + rng.normal(size=500)
    lp = lp_overlap_audit(sa, sb, o, q=0.2, alpha_lift=0.3)
    assert lp["identity_abs_err"] < 1e-14, lp
    return {"status": "PASS", "prop1_u_safe": u_safe, "prop1_u_naive": u_naive, "lp_identity_err": lp["identity_abs_err"]}


def main(argv: Optional[Sequence[str]] = None) -> int:
    parser = argparse.ArgumentParser(description="Reusable diagnostics for LLM judges and reward models.")
    sub = parser.add_subparsers(dest="cmd", required=True)
    sub.add_parser("selftest", help="Verify exact algebraic and numerical invariants.")

    p_csv = sub.add_parser("audit-csv", help="Run operating-point audit on a CSV file.")
    p_csv.add_argument("csv_path")
    p_csv.add_argument("--score-col", default="score")
    p_csv.add_argument("--gold-col", default="gold_correct")
    p_csv.add_argument("--prompt-col", default="prompt_id")
    p_csv.add_argument("--budget", type=float, default=0.05)
    p_csv.add_argument("--best-of-n", type=int, default=32)

    args = parser.parse_args(argv)
    if args.cmd == "selftest":
        print(json.dumps(selftest(), indent=2))
        return 0
    if args.cmd == "audit-csv":
        scores, gold, pids = [], [], []
        with open(args.csv_path, newline="", encoding="utf-8") as f:
            for row in csv.DictReader(f):
                scores.append(float(row[args.score_col]))
                gold.append(int(row[args.gold_col]))
                pids.append(row[args.prompt_col])
        out = {
            "n_rows": len(scores),
            "auroc_pooled": auroc_tied(scores, gold),
            "auroc_within_prompt": within_prompt_auroc(scores, gold, pids),
            "review": prec_err_at_budget(scores, gold, args.budget),
            "best_of_n": exact_best_of_n_correctness(scores, gold, pids, args.best_of_n),
        }
        print(json.dumps(out, indent=2))
        return 0
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
