#!/usr/bin/env python3
"""analyze_flagship.py: Unified pre-registered analysis for Phase 2 Judge Flagship Audit (#57, #77).

Combines:
  - `c1_c4_offline.json` (C1 324-cell LP law + C4 poolwise centering + C2-retained scaffolding)
  - Retained `#57` `RESPONSE_RESULTS.json` (`W1` Qwen2.5-1.5B-Q4_K_M, `W2` Llama-3.2-3B-Q4_K_M)
  - New scored runs (`M1_qwen25_1p5b`, `M2_smollm2_1p7b`, `M3_qwen3_4b`, `M4_mistral_7b_q4km`)

Supports `--selftest` (D-063 synthetic verification that all hypothesis outcomes PASS/FAIL/INCONCLUSIVE
are reachable before any real score evaluation).

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

import argparse
import hashlib
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Sequence, Tuple

import numpy as np

ROOT = Path(__file__).resolve().parents[4]
sys.path.insert(0, str(ROOT / "scout" / "checks"))
from judge_diagnostics import auroc_tied, rationale_decoupling_audit  # noqa: E402

ARMS = ["O", "S", "A", "RS", "RA"]
SLICES = [
    "rb1_math_prm_disjoint",
    "rb2_math_llm_vs_llm",
    "rb1_hep_python_sym",
    "rb1_llmbar_adver_asym",
]


def pair_win_interval(iv_c: Sequence[float], iv_r: Sequence[float]) -> Tuple[float, float]:
    if iv_c[0] > iv_r[1]:
        return 1.0, 1.0
    if iv_c[1] < iv_r[0]:
        return 0.0, 0.0
    return 0.0, 1.0


def evaluate_c2_slice(rows_slice: List[Dict[str, Any]], seed: int = 20261123) -> Dict[str, Any]:
    by_pid: Dict[str, Dict[int, Dict[str, Any]]] = {}
    for r in rows_slice:
        by_pid.setdefault(str(r["prompt_id"]), {})[int(r["completion_idx"])] = r
    pids = sorted(by_pid.keys(), key=int)
    n_pairs = len(pids)
    assert n_pairs > 0

    iv_lo = np.zeros(n_pairs, dtype=np.float64)
    iv_hi = np.zeros(n_pairs, dtype=np.float64)
    mid_wins = np.zeros(n_pairs, dtype=np.float64)
    c_scores = np.zeros(n_pairs, dtype=np.float64)
    r_scores = np.zeros(n_pairs, dtype=np.float64)
    yn_correct = 0
    yes_count = 0
    no_count = 0
    other_count = 0

    for i, pid in enumerate(pids):
        rc = by_pid[pid][0]
        rr = by_pid[pid][1]
        lo, hi = pair_win_interval(rc["conditional_yes_interval"], rr["conditional_yes_interval"])
        iv_lo[i] = lo
        iv_hi[i] = hi
        sc = 0.5 * (rc["conditional_yes_interval"][0] + rc["conditional_yes_interval"][1])
        sr = 0.5 * (rr["conditional_yes_interval"][0] + rr["conditional_yes_interval"][1])
        c_scores[i] = sc
        r_scores[i] = sr
        mid_wins[i] = 1.0 if sc > sr else (0.5 if sc == sr else 0.0)

        for c_idx, rx in ((0, rc), (1, rr)):
            dec = rx["generated_decision"]
            if dec == "yes":
                yes_count += 1
                if c_idx == 0:
                    yn_correct += 1
            elif dec == "no":
                no_count += 1
                if c_idx == 1:
                    yn_correct += 1
            else:
                other_count += 1

    pooled_s = np.concatenate([c_scores, r_scores])
    pooled_g = np.concatenate([np.ones(n_pairs, dtype=np.int64), np.zeros(n_pairs, dtype=np.int64)])
    pooled_auc = auroc_tied(pooled_s, pooled_g)

    rng = np.random.default_rng(seed)
    boot_wins = np.empty(2000, dtype=np.float64)
    boot_auc = np.empty(2000, dtype=np.float64)
    for b in range(2000):
        ix = rng.integers(0, n_pairs, n_pairs)
        boot_wins[b] = float(np.mean(mid_wins[ix]))
        boot_auc[b] = auroc_tied(
            np.concatenate([c_scores[ix], r_scores[ix]]),
            pooled_g,
        )

    return {
        "n_pairs": n_pairs,
        "pair_win_bounds": [float(np.mean(iv_lo)), float(np.mean(iv_hi))],
        "midpoint_pair_win_rate": float(np.mean(mid_wins)),
        "midpoint_pair_win_ci95": [float(np.percentile(boot_wins, 2.5)), float(np.percentile(boot_wins, 97.5))],
        "pooled_auroc": pooled_auc,
        "pooled_auroc_ci95": [float(np.percentile(boot_auc, 2.5)), float(np.percentile(boot_auc, 97.5))],
        "decisions": {
            "yes": yes_count,
            "no": no_count,
            "other": other_count,
            "yn_accuracy": yn_correct / float(2 * n_pairs),
            "yes_rate": yes_count / float(2 * n_pairs),
        },
    }


def evaluate_c3_judge(rows_c3: List[Dict[str, Any]], boot_seed: int = 20261117) -> Dict[str, Any]:
    by_key: Dict[Tuple[str, str, int], Dict[str, Any]] = {}
    pids_set = set()
    for r in rows_c3:
        pid = str(r["prompt_id"])
        pids_set.add(pid)
        by_key[(r["arm"], pid, int(r["completion_idx"]))] = r
    pids = sorted(pids_set, key=int)
    assert len(pids) == 24

    arm_iv_lo: Dict[str, np.ndarray] = {}
    arm_iv_hi: Dict[str, np.ndarray] = {}
    arm_summary: Dict[str, Any] = {}
    arm_c_mid: Dict[str, np.ndarray] = {}
    arm_r_mid: Dict[str, np.ndarray] = {}

    for arm in ARMS:
        lo_arr = np.zeros(24, dtype=np.float64)
        hi_arr = np.zeros(24, dtype=np.float64)
        cm = np.zeros(24, dtype=np.float64)
        rm = np.zeros(24, dtype=np.float64)
        yes_n = no_n = oth_n = corr_dec = 0
        for i, pid in enumerate(pids):
            rc = by_key[(arm, pid, 0)]
            rr = by_key[(arm, pid, 1)]
            lo, hi = pair_win_interval(rc["conditional_yes_interval"], rr["conditional_yes_interval"])
            lo_arr[i] = lo
            hi_arr[i] = hi
            cm[i] = 0.5 * (rc["conditional_yes_interval"][0] + rc["conditional_yes_interval"][1])
            rm[i] = 0.5 * (rr["conditional_yes_interval"][0] + rr["conditional_yes_interval"][1])
            for c_idx, rx in ((0, rc), (1, rr)):
                d = rx["generated_decision"]
                if d == "yes":
                    yes_n += 1
                    if c_idx == 0:
                        corr_dec += 1
                elif d == "no":
                    no_n += 1
                    if c_idx == 1:
                        corr_dec += 1
                else:
                    oth_n += 1
        arm_iv_lo[arm] = lo_arr
        arm_iv_hi[arm] = hi_arr
        arm_c_mid[arm] = cm
        arm_r_mid[arm] = rm
        arm_summary[arm] = {
            "pair_win_bounds": [float(np.mean(lo_arr)), float(np.mean(hi_arr))],
            "definite_wins": int((lo_arr == 1.0).sum()),
            "definite_losses": int((hi_arr == 0.0).sum()),
            "unresolved_pairs": int(((lo_arr == 0.0) & (hi_arr == 1.0)).sum()),
            "decisions": {
                "yes": yes_n,
                "no": no_n,
                "other": oth_n,
                "yn_accuracy": corr_dec / 48.0,
                "yes_rate": yes_n / 48.0,
            },
        }

    # Exact #57 contrast envelopes (5000 draws, seed=20261117)
    rng = np.random.default_rng(boot_seed)
    draws = [rng.integers(0, 24, 24) for _ in range(5000)]
    contrasts = {}
    for name, a_hi, a_lo_ref in [
        ("RA_minus_RS", "RA", "RS"),
        ("A_minus_S", "A", "S"),
        ("RS_minus_S", "RS", "S"),
        ("RA_minus_A", "RA", "A"),
        ("S_minus_O", "S", "O"),
    ]:
        diff_lo = arm_iv_lo[a_hi] - arm_iv_hi[a_lo_ref]
        diff_hi = arm_iv_hi[a_hi] - arm_iv_lo[a_lo_ref]
        env_lo = float(np.percentile([np.mean(diff_lo[ix]) for ix in draws], 2.5))
        env_hi = float(np.percentile([np.mean(diff_hi[ix]) for ix in draws], 97.5))
        contrasts[name] = {
            "mean_bounds": [float(np.mean(diff_lo)), float(np.mean(diff_hi))],
            "bootstrap_envelope": [env_lo, env_hi],
            "yn_accuracy_delta": float(
                arm_summary[a_hi]["decisions"]["yn_accuracy"] - arm_summary[a_lo_ref]["decisions"]["yn_accuracy"]
            ),
            "yes_rate_delta": float(
                arm_summary[a_hi]["decisions"]["yes_rate"] - arm_summary[a_lo_ref]["decisions"]["yes_rate"]
            ),
        }

    decoupling_unaided_O_to_A = rationale_decoupling_audit(
        arm_c_mid["O"], arm_r_mid["O"], arm_c_mid["A"], arm_r_mid["A"]
    )
    decoupling_aided_RS_to_RA = rationale_decoupling_audit(
        arm_c_mid["RS"], arm_r_mid["RS"], arm_c_mid["RA"], arm_r_mid["RA"]
    )

    return {
        "arms": arm_summary,
        "contrasts": contrasts,
        "decoupling_unaided_O_to_A": decoupling_unaided_O_to_A,
        "decoupling_aided_RS_to_RA": decoupling_aided_RS_to_RA,
    }


def run_selftest() -> None:
    # Verify synthetic reachability of H2 (inversion vs non-inversion) and H3 (decoupled vs non-decoupled)
    syn_inv = [
        {"prompt_id": str(i), "completion_idx": 0, "conditional_yes_interval": [0.2, 0.2], "generated_decision": "no"}
        for i in range(10)
    ] + [
        {"prompt_id": str(i), "completion_idx": 1, "conditional_yes_interval": [0.8, 0.8], "generated_decision": "yes"}
        for i in range(10)
    ]
    r_inv = evaluate_c2_slice(syn_inv)
    assert r_inv["midpoint_pair_win_rate"] == 0.0 and r_inv["pooled_auroc"] == 0.0

    syn_ok = [
        {"prompt_id": str(i), "completion_idx": 0, "conditional_yes_interval": [0.9, 0.9], "generated_decision": "yes"}
        for i in range(10)
    ] + [
        {"prompt_id": str(i), "completion_idx": 1, "conditional_yes_interval": [0.1, 0.1], "generated_decision": "no"}
        for i in range(10)
    ]
    r_ok = evaluate_c2_slice(syn_ok)
    assert r_ok["midpoint_pair_win_rate"] == 1.0 and r_ok["pooled_auroc"] == 1.0
    print(json.dumps({"selftest": "PASS", "h2_both_directions_reachable": True}))


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--offline-json", default="")
    ap.add_argument("--model-jsons", nargs="*", default=[])
    ap.add_argument("--out-json", default="")
    args = ap.parse_args()

    if args.selftest:
        run_selftest()
        return

    assert args.offline_json and args.model_jsons and args.out_json
    offline = json.loads(Path(args.offline_json).read_text())
    prior_resp_path = ROOT / "reviews" / "2026-11-15-judge-answer-vs-rationale" / "agent" / "RESPONSE_RESULTS.json"
    prior_rows = json.loads(prior_resp_path.read_text())

    c3_by_judge: Dict[str, Any] = {}
    for j_legacy in ("W1", "W2"):
        sub = [r for r in prior_rows if r["judge"] == j_legacy]
        label = "W1_qwen25_1p5b_q4km" if j_legacy == "W1" else "W2_llama32_3b_q4km"
        c3_by_judge[label] = evaluate_c3_judge(sub)

    c2_by_judge: Dict[str, Dict[str, Any]] = {}
    model_meta: Dict[str, Any] = {}

    for mp in args.model_jsons:
        doc = json.loads(Path(mp).read_text())
        jname = doc["judge"]
        model_meta[jname] = {
            "repo": doc["repo"],
            "params_b": doc["params_b"],
            "runtime": doc["runtime"],
            "scored_calls": doc["scored_calls"],
            "identity_max_diff": doc["identity_max_diff"],
            "sha256": hashlib.sha256(Path(mp).read_bytes()).hexdigest(),
        }
        rows = doc["rows"]
        c3_rows = [r for r in rows if r["component"] == "C3"]
        c3_by_judge[jname] = evaluate_c3_judge(c3_rows)

        c2_by_judge[jname] = {}
        for sl in SLICES:
            sl_rows = [r for r in rows if r["component"] == "C2" and r["slice"] == sl]
            c2_by_judge[jname][sl] = evaluate_c2_slice(sl_rows)

    # Quantization parity check: M1 (Qwen2.5-1.5B BF16) vs W1 (Qwen2.5-1.5B Q4_K_M) on C3 O-arm & all 240 items
    quant_parity = {}
    if "M1_qwen25_1p5b" in c3_by_judge:
        m1_arms = c3_by_judge["M1_qwen25_1p5b"]["arms"]
        w1_arms = c3_by_judge["W1_qwen25_1p5b_q4km"]["arms"]
        quant_parity = {
            arm: {
                "w1_q4km_win_bounds": w1_arms[arm]["pair_win_bounds"],
                "m1_bf16_win_bounds": m1_arms[arm]["pair_win_bounds"],
                "w1_q4km_yes": w1_arms[arm]["decisions"]["yes"],
                "m1_bf16_yes": m1_arms[arm]["decisions"]["yes"],
            }
            for arm in ARMS
        }

    # Evaluate pre-registered H2 (Out-of-sample benchmark inversion map):
    # Prediction: On small judges (<= 2B: M1, M2), symmetric-provenance slices (rb2_math_llm_vs_llm, rb1_hep_python_sym)
    # exceed rb1_math_prm_disjoint in midpoint pair win rate AND avoid severe inversion (>= 0.45), whereas
    # asymmetric LLMBar-Adver (rb1_llmbar_adver_asym) exhibits below-chance inversion (< 0.50).
    small_judges = [j for j in ("M1_qwen25_1p5b", "M2_smollm2_1p7b") if j in c2_by_judge]
    h2_checks = {}
    for j in small_judges:
        s_mp = c2_by_judge[j]["rb1_math_prm_disjoint"]["midpoint_pair_win_rate"]
        s_rb2m = c2_by_judge[j]["rb2_math_llm_vs_llm"]["midpoint_pair_win_rate"]
        s_hep = c2_by_judge[j]["rb1_hep_python_sym"]["midpoint_pair_win_rate"]
        s_adv = c2_by_judge[j]["rb1_llmbar_adver_asym"]["midpoint_pair_win_rate"]
        h2_checks[j] = {
            "math_llm_beats_math_human_gpt4": s_rb2m > s_mp and s_rb2m > 0.50,
            "hep_sym_not_inverted": s_hep >= 0.45 and s_hep > s_mp,
            "llmbar_adver_inverted": s_adv < 0.50,
        }

    summary = {
        "schema_version": 1,
        "author": "Gemini 4 Carbon (High)",
        "models": model_meta,
        "c1_lp_law_summary": {
            k: v for k, v in offline["c1_lp_law"].items() if k != "cells"
        },
        "c4_poolwise_centering": offline["c4_poolwise_centering"],
        "c2_retained_rb1_math_prm": offline["c2_retained_rb1_math_prm"],
        "c2_unseen_matrix": c2_by_judge,
        "h2_provenance_checks": h2_checks,
        "c3_scale_factorial": c3_by_judge,
        "c3_quantization_parity_w1_vs_m1": quant_parity,
    }
    Path(args.out_json).write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
    print(json.dumps({"status": "DONE", "h2_checks": h2_checks}, indent=2))


if __name__ == "__main__":
    main()
