#!/usr/bin/env python3
"""Zero-shared-code blind independent recompute of argument-or-pressure v2.

Reads raw results-*.json files and items_v2.json directly and verifies every
scalar metric in out/summary_v2.json within 1e-6 (both Answer-First primary
models and the Qwen3-4B Reasoning-First bridge).
"""

from __future__ import annotations

import json
import math
import random
from pathlib import Path

V2_ROOT = Path(__file__).resolve().parent.parent
OUT_DIR = V2_ROOT / "out"
IND_DIR = V2_ROOT / "independent"


def mean(xs):
    return sum(xs) / len(xs)


def sample_sd(xs):
    m = mean(xs)
    return math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1))


def bci(xs, b=2000):
    rng = random.Random(0)
    n = len(xs)
    boots = sorted(sum(xs[rng.randrange(n)] for _ in range(n)) / n for _ in range(b))
    return [round(boots[int(0.025 * b)], 2), round(boots[int(0.975 * b)], 2)]


def two_group_bci(xa, xb, b=2000):
    rng = random.Random(0)
    na, nb = len(xa), len(xb)
    boots = sorted(
        (sum(xa[rng.randrange(na)] for _ in range(na)) / na)
        - (sum(xb[rng.randrange(nb)] for _ in range(nb)) / nb)
        for _ in range(b)
    )
    return [round(boots[int(0.025 * b)], 2), round(boots[int(0.975 * b)], 2)]


def check_one(label: str, raw: dict, reported: dict, expected_list: list, expected_ids: dict, pressures, diffs: list) -> dict:
    grows = raw["greedy_rows"]
    wrows = raw.get("wobble_rows") or []

    table = {}
    item_order = [it["id"] for it in expected_list]
    for r in grows:
        assert expected_ids[r["item"]] == r["kind"]
        table.setdefault((r["kind"], r["item"]), {})[(r["argument"], r["pressure"])] = r

    rec_m = {"parse_fail_second": sum(1 for r in grows if r["second"] is None)}
    if rec_m["parse_fail_second"] != reported["parse"]["fail_second_cells"]:
        diffs.append(f"{label}.fail_second_cells: {rec_m['parse_fail_second']} != {reported['parse']['fail_second_cells']}")

    move_vecs = {}
    for kind in ("flawed", "sound"):
        sub = [table[(kind, iid)] for iid in item_order if (kind, iid) in table]
        args = ("none", "weak", "strong") if kind == "flawed" else ("none", "weak", "mistaken")
        for arg in args:
            for p in pressures:
                mv = [
                    v[("none", "off")]["second"] - v[(arg, p)]["second"]
                    for v in sub
                    if v[("none", "off")]["second"] is not None and v[(arg, p)]["second"] is not None
                ]
                move_vecs[(kind, arg, p)] = mv
                m_val = round(mean(mv), 2)
                c_val = bci(mv)
                rep_cell = reported[kind][f"move_{arg}_{p}"]
                if abs(m_val - rep_cell["mean"]) > 0.015 or c_val != rep_cell["ci95"]:
                    diffs.append(f"{label}.{kind}.move_{arg}_{p}: {(m_val, c_val)} != {(rep_cell['mean'], rep_cell['ci95'])}")
                rec_m[f"{kind}_move_{arg}_{p}"] = {"n": len(mv), "mean": m_val, "ci95": c_val}

    for p in pressures:
        fs = move_vecs[("flawed", "strong", p)]
        sw = move_vecs[("sound", "weak", p)]
        sm = move_vecs[("sound", "mistaken", p)]
        for mkey, xa, xb in [
            (f"v1_irrelevant_foil_p_{p}", fs, sw),
            (f"v2_mistaken_foil_p_{p}", fs, sm),
            (f"illusion_penalty_p_{p}", sm, sw),
        ]:
            d_val = round(mean(xa) - mean(xb), 2)
            ci_val = two_group_bci(xa, xb)
            rep_marg = reported["margins"][mkey]
            if abs(d_val - rep_marg["diff"]) > 0.015 or ci_val != rep_marg["ci95"]:
                diffs.append(f"{label}.margins.{mkey}: {(d_val, ci_val)} != {(rep_marg['diff'], rep_marg['ci95'])}")
            rec_m[mkey] = {"diff": d_val, "ci95": ci_val}

    for ck_kind, ck_arg in [("flawed", "none"), ("sound", "none"), ("flawed", "strong"), ("sound", "mistaken")]:
        key = f"{ck_kind}_{ck_arg}_off"
        sub_w = [r for r in wrows if r["kind"] == ck_kind and r["argument"] == ck_arg]
        if not sub_w:
            continue
        sds = [sample_sd([x for x in r["samples"] if x is not None]) for r in sub_w if sum(x is not None for x in r["samples"]) >= 2]
        m_sd = round(mean(sds), 2) if sds else None
        rep_sd = reported["wobble"][key]["mean_within_item_sd"]
        if m_sd is not None and abs(m_sd - rep_sd) > 1e-6:
            diffs.append(f"{label}.wobble.{key}.sd: {m_sd} != {rep_sd}")
        rec_m[f"wobble_sd_{key}"] = m_sd

    return rec_m


def main():
    items = json.loads((V2_ROOT / "items_v2.json").read_text())["items"]
    expected_ids = {it["id"]: it["kind"] for it in items}
    summary = json.loads((OUT_DIR / "summary_v2.json").read_text())

    diffs = []
    recomputed = {"models": {}, "reasoning_first_bridge": {}}

    for label, reported in summary["models"].items():
        raw = json.loads((OUT_DIR / f"results-{label}.json").read_text())
        recomputed["models"][label] = check_one(label, raw, reported, items, expected_ids, ("off", "on"), diffs)

    if summary.get("reasoning_first_bridge"):
        raw_rf = json.loads((OUT_DIR / "results-qwen3-4b-2507-reasoning-first.json").read_text())
        recomputed["reasoning_first_bridge"] = check_one(
            "qwen3-4b-2507-rf", raw_rf, summary["reasoning_first_bridge"], items, expected_ids, ("off",), diffs
        )

    OUT_PATH = IND_DIR / "RECOMPUTED.json"
    recomputed["discrepancies"] = diffs
    OUT_PATH.write_text(json.dumps(recomputed, indent=2) + "\n", encoding="utf-8")
    if diffs:
        print("DISCREPANCIES:", diffs)
        raise SystemExit(1)
    print(f"INDEPENDENT RECOMPUTE MATCHED ALL METRICS (0 discrepancies across {len(recomputed['models'])} models + RF bridge).")


if __name__ == "__main__":
    main()
