#!/usr/bin/env python3
"""run_c1_c4_offline.py: Zero-forward offline mathematical & empirical audits for Phase 2 (#57, #77).

Executes three offline components using `scout/checks/judge_diagnostics.py` (with `--dry-run` mode
for D-063 schema/gate verification before scored computation):
  - C1: Lincoln-Petersen overlap-recall exact covariance decomposition & zero-shot unlabeled-lift
        calibration (`PPE-MATH` 156 cells -> held-out `PPE-MMLU-Pro` 156 cells & `RB2` 12 cells;
        total 324 RM pair-cells across q in {0.2, 0.3}).
  - C4: Cancellation-safe poolwise centering (`papers/judge-scores` Proposition 1) across 30
        pool x RM score series under per-prompt baseline offsets C in {0, 1e4, 1e8, 1e12} plus
        controlled exact-tie injections.
  - C2-Retained: Surface-scaffolding asymmetry audit on retained `#57` `rb1mp__W1/W2.jsonl`
        restricted to the 285 verified-wrong (`reference_disagreement`) pairs in `LABELS_FROZEN.json`.

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

import argparse
import csv
import gzip
import hashlib
import itertools
import json
import math
import sys
from pathlib import Path
from typing import Any, Dict, List, Tuple

import numpy as np
import pyarrow.parquet as pq

ROOT = Path(__file__).resolve().parents[4]
sys.path.insert(0, str(ROOT / "scout" / "checks"))
from judge_diagnostics import (  # noqa: E402
    PromptClusterBoot,
    auroc_tied,
    fit_lp_lift_alpha,
    lp_overlap_audit,
    naive_pool_center,
    poolwise_u_alpha,
    safe_pool_center,
    scaffolding_score,
)

PINS = {
    "items_csv_gz": "375cc747e24e7cf6f30541ae142e79b3b0087cbbaf4e67e1c19776f832d488bb",
    "b1_gaps_json": "0efb3da50ff351dbc2baeeea00e7751e16fc0ff71683ca055c639f9ef9b829e1",
    "labels_frozen": "3cdb11e3b2f035ef3cbbced98a0a14926ac2f34976f83701b961a5a8f852144" if False else "3cdb11e3b2f035ef3cbbced98a0a14926ac2f34976f436388b09b48dd60d786d",
    "rb1_parquet": "65473c20ed0627e02503557ae102c25c6b0e66b5ed69ee327e224bb95e70ca29",
    "w1_jsonl": "6ba043110a0daf385c7cbe8c6e4a7caf555907f5d575032a9b6a98c53842d700",
    "w2_jsonl": "18903bd53a9c5ac604cf1b0402b1cd9020246ef33c9481a14e7611d3a366c5e6",
}


def sha256_file(p: Path) -> str:
    return hashlib.sha256(p.read_bytes()).hexdigest()


def spearman_rho(x: np.ndarray, y: np.ndarray) -> float:
    from judge_diagnostics import avg_ranks
    rx = avg_ranks(np.asarray(x, dtype=np.float64))
    ry = avg_ranks(np.asarray(y, dtype=np.float64))
    rx = rx - rx.mean()
    ry = ry - ry.mean()
    denom = float(np.sqrt((rx * rx).sum() * (ry * ry).sum()))
    return float((rx * ry).sum() / denom) if denom > 1e-15 else 0.0


def load_bestofk_pools(items_gz: Path) -> Dict[str, Dict[str, Any]]:
    raw: Dict[str, Dict[Tuple[str, int], Dict[str, Any]]] = {}
    judges_by_pool: Dict[str, set] = {}
    with gzip.open(items_gz, "rt", newline="") as f:
        rd = csv.DictReader(f)
        for row in rd:
            pool = row["pool"]
            jid = row["judge_id"]
            if jid == "V0":  # exclude non-RM length baseline per NOTE.md (78+78+6 = 162 pairs)
                continue
            key = (row["prompt_id"], int(row["completion_idx"]))
            d = raw.setdefault(pool, {}).setdefault(key, {"gold": int(row["gold_correct"])})
            d[jid] = float(row["score"])
            judges_by_pool.setdefault(pool, set()).add(jid)

    out: Dict[str, Dict[str, Any]] = {}
    for pool, table in raw.items():
        j_list = sorted(judges_by_pool[pool])
        keys = sorted(k for k, r in table.items() if all(j in r for j in j_list))
        pids = np.array([k[0] for k in keys])
        gold = np.array([table[k]["gold"] for k in keys], dtype=np.int64)
        scores = {j: np.array([table[k][j] for k in keys], dtype=np.float64) for j in j_list}
        out[pool] = {"judges": j_list, "pids": pids, "gold": gold, "scores": scores, "n_rows": len(keys), "n_prompts": len(set(pids))}
    return out


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--data-dir", required=True, help="Scratch directory with rb1_filtered.parquet")
    ap.add_argument("--out-json", required=True, help="Output JSON path")
    ap.add_argument("--dry-run", action="store_true", help="Verify hashes, shapes, and synthetic algebra only; emit zero scored stats")
    args = ap.parse_args()

    items_gz = ROOT / "runs" / "2026-11-14-0921-box" / "judge-table" / "cells" / "withinprompt-bestofk-20261113" / "items.csv.gz"
    b1_gaps_path = ROOT / "runs" / "2026-11-14-0921-box" / "judge-table" / "cells" / "B1-lp-gap-ci-20261114" / "gaps.json"
    labels_path = ROOT / "reviews" / "2026-11-14-judge-mismatch-prevalence" / "agent" / "LABELS_FROZEN.json"
    w1_path = ROOT / "runs" / "2026-11-14-0921-box" / "judge-table" / "cells" / "C1-debate-lite-harness" / "inputs" / "rb1mp__W1.jsonl"
    w2_path = ROOT / "runs" / "2026-11-14-0921-box" / "judge-table" / "cells" / "C1-debate-lite-harness" / "inputs" / "rb1mp__W2.jsonl"
    rb1_path = Path(args.data_dir) / "rb1_filtered.parquet"

    assert sha256_file(items_gz) == PINS["items_csv_gz"], "items.csv.gz SHA256 mismatch"
    assert sha256_file(b1_gaps_path) == PINS["b1_gaps_json"], "B1 gaps.json SHA256 mismatch"
    assert sha256_file(labels_path) == PINS["labels_frozen"], "LABELS_FROZEN SHA256 mismatch"
    assert sha256_file(rb1_path) == PINS["rb1_parquet"], "rb1_filtered.parquet SHA256 mismatch"

    pools = load_bestofk_pools(items_gz)
    pair_cell_counts = {p: len(list(itertools.combinations(d["judges"], 2))) * 2 for p, d in pools.items()}
    assert sum(pair_cell_counts.values()) == 324, f"Expected 324 RM pair-cells, got {pair_cell_counts}"

    if args.dry_run:
        # Synthetic gate checks ONLY — zero real score contrasts inspected
        rng = np.random.default_rng(42)
        syn_a = rng.normal(size=400)
        syn_b = 0.7 * syn_a + rng.normal(scale=0.7, size=400)
        syn_o = (syn_a + rng.normal(size=400) > 0).astype(int)
        lp_syn = lp_overlap_audit(syn_a, syn_b, syn_o, q=0.2)
        assert lp_syn["identity_abs_err"] <= 1e-15
        print(json.dumps({
            "dry_run": True,
            "status": "PASS",
            "pools": {p: {"n_judges": len(d["judges"]), "n_rows": d["n_rows"], "n_prompts": d["n_prompts"], "n_pair_cells": pair_cell_counts[p]} for p, d in pools.items()},
            "total_pair_cells": sum(pair_cell_counts.values()),
            "w1_rows": sum(1 for _ in w1_path.open()),
            "w2_rows": sum(1 for _ in w2_path.open()),
            "synthetic_lp_identity_err": lp_syn["identity_abs_err"],
        }, indent=2))
        return

    # ---------------- C1: 324 RM pair-cells LP law & zero-shot lift correction ----------------
    qs = [0.2, 0.3]
    raw_records_by_pool: Dict[str, List[Dict[str, Any]]] = {}
    for pool_name in ("PPE-MATH", "PPE-MMLU-Pro", "RB2"):
        d = pools[pool_name]
        recs = []
        for ja, jb in itertools.combinations(d["judges"], 2):
            for q in qs:
                res = lp_overlap_audit(d["scores"][ja], d["scores"][jb], d["gold"], q=q, alpha_lift=0.0)
                res["pool"] = pool_name
                res["pair"] = f"{ja}+{jb}"
                recs.append(res)
        raw_records_by_pool[pool_name] = recs

    # Fit 1-parameter alpha_hat ONLY on PPE-MATH (156 cells)
    alpha_hat = fit_lp_lift_alpha(raw_records_by_pool["PPE-MATH"])

    c1_summary_by_pool: Dict[str, Any] = {}
    all_cells_out: List[Dict[str, Any]] = []
    max_identity_err = 0.0

    for idx_p, pool_name in enumerate(("PPE-MATH", "PPE-MMLU-Pro", "RB2")):
        d = pools[pool_name]
        cells = []
        for ja, jb in itertools.combinations(d["judges"], 2):
            for q in qs:
                res = lp_overlap_audit(d["scores"][ja], d["scores"][jb], d["gold"], q=q, alpha_lift=alpha_hat)
                res["pool"] = pool_name
                res["pair"] = f"{ja}+{jb}"
                max_identity_err = max(max_identity_err, res["identity_abs_err"])
                cells.append(res)
                all_cells_out.append(res)

        lp_gaps = np.array([c["lp_gap"] for c in cells], dtype=np.float64)
        adj_gaps = np.array([c["adj_gap"] for c in cells], dtype=np.float64)
        lu_excess = np.array([c["lambda_unlab"] - 1.0 for c in cells], dtype=np.float64)
        rmse_lp = float(np.sqrt(np.mean(lp_gaps ** 2)))
        rmse_adj = float(np.sqrt(np.mean(adj_gaps ** 2)))

        # Paired prompt-cluster bootstrap for pool-mean lp_gap and pool-mean adj_gap (B=400)
        boot = PromptClusterBoot(d["pids"], n_boot=400, seed=20261123 + idx_p)
        pairs_list = list(itertools.combinations(d["judges"], 2))

        def mean_gaps_boot(ix: np.ndarray) -> Tuple[float, float]:
            g_lp, g_adj = [], []
            for ja, jb in pairs_list:
                for q in qs:
                    r = lp_overlap_audit(d["scores"][ja][ix], d["scores"][jb][ix], d["gold"][ix], q=q, alpha_lift=alpha_hat)
                    if math.isfinite(r["lp_gap"]):
                        g_lp.append(r["lp_gap"])
                        g_adj.append(r["adj_gap"])
            return float(np.mean(g_lp)), float(np.mean(g_adj))

        boot_pairs = [mean_gaps_boot(ix) for ix in boot.idx]
        lp_boot = np.array([bp[0] for bp in boot_pairs], dtype=np.float64)
        adj_boot = np.array([bp[1] for bp in boot_pairs], dtype=np.float64)

        c1_summary_by_pool[pool_name] = {
            "role": "calibration_fit" if pool_name == "PPE-MATH" else "held_out_oos",
            "n_cells": len(cells),
            "mean_lp_gap": float(np.mean(lp_gaps)),
            "mean_lp_gap_ci95": [float(np.percentile(lp_boot, 2.5)), float(np.percentile(lp_boot, 97.5))],
            "mean_adj_gap": float(np.mean(adj_gaps)),
            "mean_adj_gap_ci95": [float(np.percentile(adj_boot, 2.5)), float(np.percentile(adj_boot, 97.5))],
            "rmse_lp": rmse_lp,
            "rmse_adj": rmse_adj,
            "rel_rmse_change": float((rmse_adj - rmse_lp) / rmse_lp),
            "median_abs_lp_gap": float(np.median(np.abs(lp_gaps))),
            "median_abs_adj_gap": float(np.median(np.abs(adj_gaps))),
            "frac_cells_abs_error_reduced": float(np.mean(np.abs(adj_gaps) < np.abs(lp_gaps))),
            "frac_cells_lp_positive": float(np.mean(lp_gaps > 0)),
            "spearman_unlab_lift_vs_lp_gap": spearman_rho(lu_excess, lp_gaps),
        }

    assert max_identity_err <= 1e-12, f"Gate LP-ID failed: {max_identity_err}"
    h1_pass = (
        c1_summary_by_pool["PPE-MMLU-Pro"]["rel_rmse_change"] <= -0.25
        and c1_summary_by_pool["RB2"]["rmse_adj"] <= c1_summary_by_pool["RB2"]["rmse_lp"]
    )

    # ---------------- C4: Cancellation-safe poolwise centering audit ----------------
    def eval_safe_vs_naive(scores: np.ndarray, gold: np.ndarray, pids: np.ndarray, alpha: float = 0.3) -> Dict[str, float]:
        _, inv = np.unique(pids, return_inverse=True)
        order = np.argsort(inv, kind="mergesort")
        cnt = np.bincount(inv)
        starts = np.cumsum(cnt) - cnt
        res_safe, res_naive, ws, ys = [], [], [], []
        within_ties_broken = 0
        within_ties_total = 0
        for g in range(len(cnt)):
            ix = order[starts[g]:starts[g] + cnt[g]]
            sg = scores[ix]
            yg = gold[ix]
            # Slightly non-uniform candidate weights (as in importance-weighted / empirical decoding pools)
            wg = 1.0 + 0.01 * np.arange(len(sg), dtype=np.float64)
            wg = wg / wg.sum()
            rs = safe_pool_center(sg, wg)
            rn = naive_pool_center(sg, wg)
            # Check exact score ties inside prompt
            for i1 in range(len(sg)):
                for i2 in range(i1 + 1, len(sg)):
                    if sg[i1] == sg[i2]:
                        within_ties_total += 1
                        if rn[i1] != rn[i2]:
                            within_ties_broken += 1
            res_safe.append(rs)
            res_naive.append(rn)
            ws.append(wg)
            ys.append(yg)
        u_safe = poolwise_u_alpha(res_safe, ws, ys, alpha=alpha)
        u_naive = poolwise_u_alpha(res_naive, ws, ys, alpha=alpha)
        return {
            "u_alpha_safe": float(u_safe),
            "u_alpha_naive": float(u_naive),
            "abs_u_diff": float(abs(u_safe - u_naive)),
            "within_ties_total": within_ties_total,
            "within_ties_broken_naive": within_ties_broken,
        }

    offsets = [0.0, 1e4, 1e8, 1e12, 1e15]
    c4_by_offset: Dict[str, Any] = {}
    for C in offsets:
        max_u_diff = 0.0
        corrupted_series = 0
        total_series = 0
        for pool_name in ("PPE-MATH", "PPE-MMLU-Pro", "RB2"):
            d = pools[pool_name]
            _, inv = np.unique(d["pids"], return_inverse=True)
            shift = C * (1.0 + 0.13 * np.sin(inv.astype(np.float64) + 1.0))
            for j in d["judges"]:
                total_series += 1
                res = eval_safe_vs_naive(d["scores"][j] + shift, d["gold"], d["pids"], alpha=0.3)
                max_u_diff = max(max_u_diff, res["abs_u_diff"])
                if res["abs_u_diff"] > 1e-9:
                    corrupted_series += 1
        c4_by_offset[f"{C:.0e}"] = {
            "offset": C,
            "total_series": total_series,
            "series_with_u_drift_gt_1e9": corrupted_series,
            "max_abs_u_alpha_drift": max_u_diff,
        }

    # Discrete 5-point rubric quantization on real PPE-MATH J1 + extreme probability mass (Proposition 1 regime)
    d_math = pools["PPE-MATH"]
    _, inv_m = np.unique(d_math["pids"], return_inverse=True)
    s_rubric = np.round(d_math["scores"]["J1"] * 2.0) / 2.0
    c4_rubric_ties: Dict[str, Any] = {}
    for C in [0.0, 1e8, 1e12, 1e15]:
        shift_m = C * (1.0 + 0.13 * np.sin(inv_m.astype(np.float64) + 1.0))
        c4_rubric_ties[f"{C:.0e}"] = eval_safe_vs_naive(s_rubric + shift_m, d_math["gold"], d_math["pids"], alpha=0.3)

    # ---------------- C2-Retained: Scaffolding stratification on #57 rb1mp W1 & W2 ----------------
    rb1_mp = {
        str(r["id"]): r
        for r in pq.read_table(rb1_path).to_pylist()
        if r["subset"] == "math-prm"
    }
    labels = {(str(r["prompt_id"]), int(r["completion_idx"])): r for r in json.loads(labels_path.read_text())}
    verified_pids = sorted(
        [pid for pid in rb1_mp if labels[(pid, 1)]["classification"] == "reference_disagreement"],
        key=int,
    )
    assert len(verified_pids) == 285

    def load_judge_jsonl(p: Path) -> Dict[Tuple[str, int], float]:
        out_s = {}
        for line in p.read_text().splitlines():
            if not line.strip():
                continue
            r = json.loads(line)
            out_s[(str(r["prompt_id"]), int(r["completion_idx"]))] = float(r["score"])
        return out_s

    w1_s = load_judge_jsonl(w1_path)
    w2_s = load_judge_jsonl(w2_path)

    delta_scaf = np.array(
        [scaffolding_score(rb1_mp[pid]["chosen"]) - scaffolding_score(rb1_mp[pid]["rejected"]) for pid in verified_pids],
        dtype=np.float64,
    )
    delta_words = np.array(
        [len(rb1_mp[pid]["chosen"].split()) - len(rb1_mp[pid]["rejected"].split()) for pid in verified_pids],
        dtype=np.float64,
    )

    q1, q2 = np.percentile(delta_scaf, [33.3333, 66.6667])
    tertile_masks = {
        "T1_rejected_heavily_scaffolded": delta_scaf <= q1,
        "T2_middle_asymmetry": (delta_scaf > q1) & (delta_scaf <= q2),
        "T3_least_asymmetric_or_chosen_higher": delta_scaf > q2,
        "subset_delta_scaf_ge_0": delta_scaf >= 0.0,
    }

    c2_retained: Dict[str, Any] = {
        "n_verified_disagreement_pairs": len(verified_pids),
        "mean_delta_scaffolding": float(np.mean(delta_scaf)),
        "frac_rejected_more_scaffolded": float(np.mean(delta_scaf < 0)),
        "mean_delta_words": float(np.mean(delta_words)),
        "tertile_cutpoints": [float(q1), float(q2)],
        "judges": {},
    }

    rng_b = np.random.default_rng(20261123)
    boot_ix = [rng_b.integers(0, len(verified_pids), len(verified_pids)) for _ in range(2000)]

    for jname, s_map in (("W1_qwen25_1p5b", w1_s), ("W2_llama32_3b", w2_s)):
        sc_diff = np.array([s_map[(pid, 0)] - s_map[(pid, 1)] for pid in verified_pids], dtype=np.float64)
        wins = (sc_diff > 0).astype(np.float64) + 0.5 * (sc_diff == 0).astype(np.float64)
        # Pooled AUROC over the 570 responses
        pooled_scores = np.array([s_map[(pid, c)] for pid in verified_pids for c in (0, 1)], dtype=np.float64)
        pooled_gold = np.array([1 - c for pid in verified_pids for c in (0, 1)], dtype=np.int64)

        rho_scaf = spearman_rho(delta_scaf, sc_diff)
        rho_boot = np.array([spearman_rho(delta_scaf[ix], sc_diff[ix]) for ix in boot_ix], dtype=np.float64)

        strata_out = {}
        for k_m, mask in tertile_masks.items():
            n_m = int(mask.sum())
            strata_out[k_m] = {
                "n_pairs": n_m,
                "mean_delta_scaffolding": float(np.mean(delta_scaf[mask])) if n_m else float("nan"),
                "pair_win_rate": float(np.mean(wins[mask])) if n_m else float("nan"),
            }
        t3_minus_t1_boot = np.array(
            [
                float(np.mean(wins[ix][delta_scaf[ix] > q2]) - np.mean(wins[ix][delta_scaf[ix] <= q1]))
                for ix in boot_ix
            ],
            dtype=np.float64,
        )
        c2_retained["judges"][jname] = {
            "overall_pair_win_rate": float(np.mean(wins)),
            "overall_pooled_auroc": auroc_tied(pooled_scores, pooled_gold),
            "spearman_delta_scaffolding_vs_margin": rho_scaf,
            "spearman_ci95": [float(np.percentile(rho_boot, 2.5)), float(np.percentile(rho_boot, 97.5))],
            "t3_minus_t1_win_rate": float(
                strata_out["T3_least_asymmetric_or_chosen_higher"]["pair_win_rate"]
                - strata_out["T1_rejected_heavily_scaffolded"]["pair_win_rate"]
            ),
            "t3_minus_t1_ci95": [float(np.percentile(t3_minus_t1_boot, 2.5)), float(np.percentile(t3_minus_t1_boot, 97.5))],
            "strata": strata_out,
        }

    out = {
        "schema_version": 1,
        "author": "Gemini 4 Carbon (High)",
        "c1_lp_law": {
            "gate_lp_identity_pass": True,
            "max_identity_abs_err": max_identity_err,
            "alpha_hat_fit_on_ppe_math_only": alpha_hat,
            "h1_oos_pass": h1_pass,
            "by_pool": c1_summary_by_pool,
            "cells": all_cells_out,
        },
        "c4_poolwise_centering": {
            "continuous_rm_scores_by_offset": c4_by_offset,
            "discrete_rubric_ties_ppe_math_J1": c4_rubric_ties,
        },
        "c2_retained_rb1_math_prm": c2_retained,
    }
    out_p = Path(args.out_json)
    out_p.parent.mkdir(parents=True, exist_ok=True)
    out_p.write_text(json.dumps(out, indent=2, sort_keys=True) + "\n")
    print(json.dumps({
        "status": "DONE",
        "alpha_hat": round(alpha_hat, 4),
        "h1_oos_pass": h1_pass,
        "c1_summary": {
            k: {
                "rmse_lp": round(v["rmse_lp"], 4),
                "rmse_adj": round(v["rmse_adj"], 4),
                "rel_rmse_change": round(v["rel_rmse_change"], 4),
            }
            for k, v in c1_summary_by_pool.items()
        },
        "c2_retained_t3_minus_t1": {
            k: round(v["t3_minus_t1_win_rate"], 4) for k, v in c2_retained["judges"].items()
        },
    }, indent=2))


if __name__ == "__main__":
    main()
