#!/usr/bin/env python3
"""Arm 2: Score 1,200 controlled 2x2 pre-cutoff arguments across all 3 judge models
sequentially (batch_size=1): plain, instructed, hard_to_vary (E[1..5]),
100-item scale_reversal + greedy 0-100 sanity bridge, and order-swapped pairwise
(Strong-YES vs Strong-NO + both conflict pairs)."""
import argparse
import json
import os
import random
import time
from pathlib import Path

from judge_utils import (
    MODELS,
    build_token_groups,
    format_chat,
    greedy_text,
    load_judge,
    next_logprobs,
    parse_0_100,
    score_1_5,
    score_ab,
    unload_judge,
)

ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"
OUT_DIR = ROOT / "out"


def load_jsonl(p: Path):
    return [json.loads(line) for line in p.read_text().splitlines() if line.strip()]


def atomic_write_jsonl(p: Path, rows):
    tmp = p.with_suffix(".jsonl.tmp")
    with open(tmp, "w") as f:
        for r in rows:
            f.write(json.dumps(r) + "\n")
    os.replace(tmp, p)


def pick_subset_100(arm2_rows):
    rng = random.Random(20261123)
    by_src_y = {}
    for r in arm2_rows:
        by_src_y.setdefault((r["source"], r["resolved_to"]), []).append(r["id"])
    quotas = {
        ("manifold", 1): 12, ("manifold", 0): 12,
        ("metaculus", 1): 12, ("metaculus", 0): 12,
        ("polymarket", 1): 26, ("polymarket", 0): 26,
    }
    sub = set()
    for k, n_k in quotas.items():
        pool = sorted(by_src_y[k])
        rng.shuffle(pool)
        sub.update(pool[:n_k])
    assert len(sub) == 100
    return sub


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--models", nargs="+", default=None, help="Optional subset of model labels to run")
    args_cli = parser.parse_args()
    selected_models = set(args_cli.models) if args_cli.models else {m[0] for m in MODELS}

    arm2_rows = load_jsonl(DATA_DIR / "arm2_arguments.jsonl")
    sub100 = pick_subset_100(arm2_rows)
    cells = [("YES", "strong"), ("YES", "weak"), ("NO", "strong"), ("NO", "weak")]

    out_path = DATA_DIR / "arm2_scores.jsonl"
    # Allow per-(model, id) resume if interrupted
    by_model = {}
    if out_path.exists():
        for r in load_jsonl(out_path):
            by_model.setdefault(r["model"], {})[r["id"]] = r
    done_models = {m for m, mdict in by_model.items() if len(mdict) == len(arm2_rows)}
    if done_models:
        print("Resuming; already complete models:", sorted(done_models), flush=True)

    meta_path = OUT_DIR / "arm2_run_meta.json"
    run_meta = json.loads(meta_path.read_text()) if meta_path.exists() else {}

    def flush_all():
        ordered_rows = []
        for label_m, _, _, _ in MODELS:
            mdict = by_model.get(label_m, {})
            for q in arm2_rows:
                if q["id"] in mdict:
                    ordered_rows.append(mdict[q["id"]])
        atomic_write_jsonl(out_path, ordered_rows)

    for label, repo_id, rev, is_q3 in MODELS:
        if label not in selected_models or label in done_models:
            continue
        t0 = time.time()
        mdict = by_model.setdefault(label, {})
        if mdict:
            print(f"\n[Arm 2] Resuming {label} from {len(mdict)}/{len(arm2_rows)} items...", flush=True)
        else:
            print(f"\n[Arm 2] Loading {label} ({repo_id}@{rev[:10]})...", flush=True)
        model, tok, dev = load_judge(repo_id, rev)
        groups = build_token_groups(tok)

        newly_scored = 0
        for idx, q in enumerate(arm2_rows):
            if q["id"] in mdict:
                continue
            qtxt = q["question"]
            args = q["args"]
            in_sub = q["id"] in sub100
            rec = {"model": label, "id": q["id"], "in_sub100": in_sub, "pointwise": {}, "pairwise": {}}

            for side, qual in cells:
                key = f"{side}_{qual}"
                arg = args[key]

                p_plain = (
                    f"Question: {qtxt}\n\nProposed argument for {side}: {arg}\n\n"
                    "Rate the epistemic strength of this argument from 1 (very poor) to 5 (excellent). "
                    "Reply with only a single digit from 1 to 5."
                )
                p_inst = (
                    f"Question: {qtxt}\n\nProposed argument for {side}: {arg}\n\n"
                    "Judge only how well this argument supports its conclusion, ignoring your own belief about what the outcome of the question will be. "
                    "Rate the argument from 1 (no support) to 5 (strong support). Reply with only a single digit from 1 to 5."
                )
                p_htv = (
                    f"Question: {qtxt}\n\nProposed argument for {side}: {arg}\n\n"
                    "Apply David Deutsch's hard-to-vary criterion: evaluate whether this argument provides specific, hard-to-vary causal details, base rates, and falsifiable conditions, "
                    "or whether its claims are generic, circular, and easily swapped to argue the opposite. Ignore your own belief about the outcome. "
                    "Rate how hard-to-vary and well-grounded the argument is from 1 (completely arbitrary) to 5 (hard to vary and well-grounded). "
                    "Reply with only a single digit from 1 to 5."
                )

                cell_out = {}
                for pname, prompt in [("plain", p_plain), ("instructed", p_inst), ("hard_to_vary", p_htv)]:
                    lp = next_logprobs(model, tok, format_chat(tok, prompt, is_q3), dev)
                    sc, mass, _ = score_1_5(lp, groups)
                    cell_out[pname] = round(sc, 6)
                    cell_out[f"{pname}_mass"] = round(mass, 4)

                if in_sub:
                    p_rev = (
                        f"Question: {qtxt}\n\nProposed argument for {side}: {arg}\n\n"
                        "Judge only how well this argument supports its conclusion, ignoring your own belief about what the outcome of the question will be. "
                        "Rate the argument on a reversed scale from 1 (strong support) to 5 (no support). Reply with only a single digit from 1 to 5."
                    )
                    lp_rev = next_logprobs(model, tok, format_chat(tok, p_rev, is_q3), dev)
                    sc_rev_raw, mass_rev, _ = score_1_5(lp_rev, groups)
                    cell_out["scale_rev_raw"] = round(sc_rev_raw, 6)
                    cell_out["scale_rev_aligned"] = round(6.0 - sc_rev_raw, 6)
                    cell_out["scale_rev_mass"] = round(mass_rev, 4)

                    if qual == "strong":
                        for ptag, p00 in [
                            ("g100_plain", f"Question: {qtxt}\n\nProposed argument for {side}: {arg}\n\nHow good is this argument? Reply with only a number from 0 (very poor) to 100 (excellent)."),
                            ("g100_inst", f"Question: {qtxt}\n\nProposed argument for {side}: {arg}\n\nJudge only how well this argument supports its conclusion, ignoring what you already believe about the outcome. Reply with only a number from 0 (no support) to 100 (conclusive support)."),
                        ]:
                            raw_txt = greedy_text(model, tok, format_chat(tok, p00, is_q3), dev, max_new_tokens=8)
                            val, _ = parse_0_100(raw_txt)
                            cell_out[ptag] = val

                rec["pointwise"][key] = cell_out

            # Order-swapped pairwise comparisons
            pair_specs = [
                ("strong_yes_vs_no", args["YES_strong"], args["NO_strong"]),
                ("weak_yes_vs_strong_no", args["YES_weak"], args["NO_strong"]),
                ("weak_no_vs_strong_yes", args["NO_weak"], args["YES_strong"]),
            ]
            for pk, arg1, arg2 in pair_specs:
                p_ab = (
                    f"Question: {qtxt}\n\nArgument A: {arg1}\n\nArgument B: {arg2}\n\n"
                    "Judge which argument gives stronger, better-grounded epistemic support for its side, ignoring your own belief about the outcome. "
                    "Reply with only 'A' or 'B'."
                )
                p_ba = (
                    f"Question: {qtxt}\n\nArgument A: {arg2}\n\nArgument B: {arg1}\n\n"
                    "Judge which argument gives stronger, better-grounded epistemic support for its side, ignoring your own belief about the outcome. "
                    "Reply with only 'A' or 'B'."
                )
                ell_ab, m_ab = score_ab(next_logprobs(model, tok, format_chat(tok, p_ab, is_q3), dev), groups)
                ell_ba, m_ba = score_ab(next_logprobs(model, tok, format_chat(tok, p_ba, is_q3), dev), groups)
                # ell_ab = log P(1st)/P(2nd), ell_ba = log P(2nd)/P(1st) -> avg logodds(1st > 2nd) = 0.5*(ell_ab - ell_ba)
                rec["pairwise"][pk] = {
                    "logodds_1_over_2": round(0.5 * (ell_ab - ell_ba), 6),
                    "ell_ab": round(ell_ab, 6),
                    "ell_ba": round(ell_ba, 6),
                    "mass_min": round(min(m_ab, m_ba), 4),
                }

            mdict[q["id"]] = rec
            newly_scored += 1
            if (idx + 1) % 25 == 0:
                print(f"  {label}: {idx+1}/{len(arm2_rows)} (new={newly_scored}, {time.time()-t0:.1f}s)", flush=True)
                flush_all()

        unload_judge(model, dev)
        flush_all()
        run_meta[label] = {"wall_s": round(time.time() - t0, 1), "n": len(mdict)}
        meta_path.write_text(json.dumps(run_meta, indent=2))
        print(f"  Saved {label}: {run_meta[label]}", flush=True)

    meta_path.write_text(json.dumps(run_meta, indent=2))
    print("\nArm 2 scoring complete:", out_path, flush=True)


if __name__ == "__main__":
    main()
