#!/usr/bin/env python3
"""Analyse v2 argument-or-pressure results across greedy T=0, T=0.7 wobble, and Reasoning-First bridge."""

from __future__ import annotations

import json
import random
import re
import statistics as st
from pathlib import Path
from typing import Dict, List, Optional, Sequence

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

MODELS_ORDER = ("qwen2.5-1.5b", "smollm2-1.7b", "qwen3-4b-2507")
NEG_RE = re.compile(r"\b(not|unlikely|incorrect|wrong|flawed|doesn't|does not|cannot|can't)\b", re.I)


def bootstrap_ci(vals: Sequence[float], *, n_boot: int = 2000, seed: int = 0) -> Optional[List[float]]:
    clean = [float(x) for x in vals if x is not None]
    if not clean:
        return None
    rng = random.Random(seed)
    n = len(clean)
    draws = sorted(sum(clean[rng.randrange(n)] for _ in range(n)) / n for _ in range(n_boot))
    return [round(draws[int(0.025 * n_boot)], 2), round(draws[int(0.975 * n_boot)], 2)]


def summarize(vals: Sequence[Optional[float]]) -> dict:
    clean = [float(x) for x in vals if x is not None]
    if not clean:
        return {"n": 0, "mean": None, "sd": None, "ci95": None}
    return {
        "n": len(clean),
        "mean": round(st.mean(clean), 2),
        "sd": round(st.stdev(clean), 2) if len(clean) > 1 else 0.0,
        "ci95": bootstrap_ci(clean),
    }


def diff_two_groups(vals_a: List[Optional[float]], vals_b: List[Optional[float]]) -> dict:
    ca = [float(x) for x in vals_a if x is not None]
    cb = [float(x) for x in vals_b if x is not None]
    if not ca or not cb:
        return {"n_a": len(ca), "n_b": len(cb), "diff": None, "ci95": None}
    rng = random.Random(0)
    boots = sorted(
        (sum(ca[rng.randrange(len(ca))] for _ in range(len(ca))) / len(ca))
        - (sum(cb[rng.randrange(len(cb))] for _ in range(len(cb))) / len(cb))
        for _ in range(2000)
    )
    return {
        "n_a": len(ca),
        "n_b": len(cb),
        "diff": round(st.mean(ca) - st.mean(cb), 2),
        "ci95": [round(boots[int(0.025 * 2000)], 2), round(boots[int(0.975 * 2000)], 2)],
    }


def analyse_model(doc: dict, *, pressures: Sequence[str] = ("off", "on")) -> dict:
    rows = doc["greedy_rows"]
    wobble_rows = doc.get("wobble_rows") or []

    by_item: Dict[str, Dict[tuple, dict]] = {}
    for r in rows:
        by_item.setdefault(r["item"], {})[(r["argument"], r["pressure"])] = r

    all_first = {r["item"]: r["first"] for r in rows}
    parse_fail_first = sum(1 for v in all_first.values() if v is None)
    parse_fail_second = sum(1 for r in rows if r["second"] is None)

    summary_kind = {}
    for kind in ("flawed", "sound"):
        sub = {k: v for k, v in by_item.items() if next(iter(v.values()))["kind"] == kind}
        firsts = [next(iter(v.values()))["first"] for v in sub.values()]
        neutrals = [v[("none", "off")]["second"] for v in sub.values()]
        neutral_shifts = [f - n for f, n in zip(firsts, neutrals) if f is not None and n is not None]
        k_out = {
            "items": len(sub),
            "first": summarize(firsts),
            "neutral": summarize(neutrals),
            "neutral_shift_first_minus_neutral": summarize(neutral_shifts),
            "neutral_changed_count": sum(
                1 for f, n in zip(firsts, neutrals) if f is not None and n is not None and f != n
            ),
        }
        arg_list = ("none", "weak", "strong") if kind == "flawed" else ("none", "weak", "mistaken")
        for arg in arg_list:
            for p in pressures:
                moves = []
                raws = []
                for v in sub.values():
                    c = v[(arg, p)]["second"]
                    n = v[("none", "off")]["second"]
                    raws.append(c)
                    moves.append(None if (c is None or n is None) else (n - c))
                k_out[f"raw_{arg}_{p}"] = summarize(raws)
                k_out[f"move_{arg}_{p}"] = summarize(moves)

        if kind == "flawed":
            for p in pressures:
                diffs = [
                    None
                    if (v[("strong", p)]["second"] is None or v[("weak", p)]["second"] is None)
                    else (v[("weak", p)]["second"] - v[("strong", p)]["second"])
                    for v in sub.values()
                ]
                k_out[f"strong_minus_weak_{p}"] = summarize(diffs)
        else:
            for p in pressures:
                diffs = [
                    None
                    if (v[("mistaken", p)]["second"] is None or v[("weak", p)]["second"] is None)
                    else (v[("weak", p)]["second"] - v[("mistaken", p)]["second"])
                    for v in sub.values()
                ]
                k_out[f"mistaken_minus_weak_{p}"] = summarize(diffs)

        summary_kind[kind] = k_out

    flawed_sub = {k: v for k, v in by_item.items() if next(iter(v.values()))["kind"] == "flawed"}
    sound_sub = {k: v for k, v in by_item.items() if next(iter(v.values()))["kind"] == "sound"}

    def move_vec(sub_map: dict, arg: str, p: str) -> List[Optional[float]]:
        return [
            None if (v[("none", "off")]["second"] is None or v[(arg, p)]["second"] is None)
            else (v[("none", "off")]["second"] - v[(arg, p)]["second"])
            for v in sub_map.values()
        ]

    margins = {}
    for p in pressures:
        f_strong = move_vec(flawed_sub, "strong", p)
        s_weak = move_vec(sound_sub, "weak", p)
        s_mistaken = move_vec(sound_sub, "mistaken", p)
        margins[f"v1_irrelevant_foil_p_{p}"] = diff_two_groups(f_strong, s_weak)
        margins[f"v2_mistaken_foil_p_{p}"] = diff_two_groups(f_strong, s_mistaken)
        margins[f"illusion_penalty_p_{p}"] = diff_two_groups(s_mistaken, s_weak)

    wobble_summary = {}
    if wobble_rows:
        for ck_kind, ck_arg in [("flawed", "none"), ("sound", "none"), ("flawed", "strong"), ("sound", "mistaken")]:
            sub_w = [r for r in wobble_rows if r["kind"] == ck_kind and r["argument"] == ck_arg]
            item_sds = []
            abs_greedy_gap = []
            n_draws = 0
            n_parsed = 0
            for wr in sub_w:
                vals = [float(x) for x in wr["samples"] if x is not None]
                n_draws += len(wr["samples"])
                n_parsed += len(vals)
                if len(vals) >= 2:
                    item_sds.append(st.stdev(vals))
                if vals and wr["greedy_second"] is not None:
                    abs_greedy_gap.append(abs(float(wr["greedy_second"]) - st.mean(vals)))
            wobble_summary[f"{ck_kind}_{ck_arg}_off"] = {
                "items": len(sub_w),
                "draws_parsed": n_parsed,
                "draws_total": n_draws,
                "mean_within_item_sd": round(st.mean(item_sds), 2) if item_sds else None,
                "max_within_item_sd": round(max(item_sds), 2) if item_sds else None,
                "mean_abs_greedy_minus_t07_mean": round(st.mean(abs_greedy_gap), 2) if abs_greedy_gap else None,
            }

    scale_flips = [
        {"item": r["item"], "cell": f"{r['argument']}/{r['pressure']}", "first": r["first"], "second": r["second"]}
        for r in rows
        if r["second"] is not None
        and r["first"] is not None
        and r["second"] >= 60
        and r["second"] > r["first"]
        and NEG_RE.search((r["second_reply"] or "").split("P(true)")[0])
    ]

    return {
        "model": doc["model"],
        "protocol": doc.get("protocol", "answer_first"),
        "repo_id": doc.get("repo_id"),
        "revision": doc.get("revision"),
        "elapsed_s": doc.get("elapsed_s"),
        "parse": {
            "total_greedy_cells": len(rows),
            "fail_first_items": parse_fail_first,
            "fail_second_cells": parse_fail_second,
        },
        "flawed": summary_kind["flawed"],
        "sound": summary_kind["sound"],
        "margins": margins,
        "wobble": wobble_summary,
        "possible_scale_flips_count": len(scale_flips),
    }


def main() -> None:
    out = {
        "version": "v2, 2026-11-24",
        "move_definition": "P_neutral(none, off) - P(cell), in points; positive = moved toward critic",
        "models": {},
        "reasoning_first_bridge": {},
    }
    for label in MODELS_ORDER:
        p = OUT_DIR / f"results-{label}.json"
        if p.is_file():
            out["models"][label] = analyse_model(json.loads(p.read_text(encoding="utf-8")))

    rf_path = OUT_DIR / "results-qwen3-4b-2507-reasoning-first.json"
    if rf_path.is_file():
        out["reasoning_first_bridge"] = analyse_model(
            json.loads(rf_path.read_text(encoding="utf-8")), pressures=("off",)
        )

    out_path = OUT_DIR / "summary_v2.json"
    out_path.write_text(json.dumps(out, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(f"Wrote {out_path}")


if __name__ == "__main__":
    main()
