#!/usr/bin/env python3
"""Arm 3: Score real human pre-resolution arguments (Arm 3A ForecastBench 2024-07-21
superforecasters & Arm 3B 2026 Manifold positioned comments), verbatim and [PROB]-redacted,
respecting each judge model's strict post-cutoff resolution window (batch_size=1)."""
import argparse
import json
import os
import time
from pathlib import Path

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

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

ELIG_KEY = {
    "qwen2.5-1.5b": "eligible_qwen25",
    "smollm2-1.7b": "eligible_smollm2",
    "qwen3-4b-2507": "eligible_qwen3",
}


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 row in rows:
            f.write(json.dumps(row) + "\n")
    os.replace(tmp, p)


def swapped_ab(model, tok, dev, groups, is_q3, qtxt, arg1, arg2, rubric="instructed"):
    if rubric == "hard_to_vary":
        tail = (
            "Apply David Deutsch's hard-to-vary criterion: which argument gives more specific, hard-to-vary causal details, base rates, and falsifiable conditions rather than generic claims? "
            "Ignore your own belief about the outcome. Reply with only 'A' or 'B'."
        )
    else:
        tail = (
            "Judge which argument gives stronger, better-grounded epistemic support for its view, ignoring your own belief about the outcome. "
            "Reply with only 'A' or 'B'."
        )
    p_ab = f"Question: {qtxt}\n\nArgument A: {arg1}\n\nArgument B: {arg2}\n\n{tail}"
    p_ba = f"Question: {qtxt}\n\nArgument A: {arg2}\n\nArgument B: {arg1}\n\n{tail}"
    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)
    return {
        "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),
    }


def score_single(model, tok, dev, groups, is_q3, qtxt, arg, rubric="instructed"):
    if rubric == "hard_to_vary":
        tail = (
            "Apply David Deutsch's hard-to-vary criterion: evaluate whether this reasoning provides specific, hard-to-vary causal details, base rates, and falsifiable conditions, "
            "or generic/interchangeable claims. Ignore your own belief about the outcome. "
            "Rate how hard-to-vary and well-grounded it is from 1 (completely arbitrary) to 5 (hard to vary and well-grounded). "
            "Reply with only a single digit from 1 to 5."
        )
    else:
        tail = (
            "Judge only how well this reasoning supports its view, ignoring your own belief about what the outcome will be. "
            "Rate the argument from 1 (no support) to 5 (strong support). Reply with only a single digit from 1 to 5."
        )
    p = f"Question: {qtxt}\n\nForecaster reasoning: {arg}\n\n{tail}"
    sc, mass, _ = score_1_5(next_logprobs(model, tok, format_chat(tok, p, is_q3), dev), groups)
    return round(sc, 6), round(mass, 4)


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}

    p3a = load_jsonl(DATA_DIR / "arm3a_pairs.jsonl")
    i3a = load_jsonl(DATA_DIR / "arm3a_individual.jsonl")
    p3b = load_jsonl(DATA_DIR / "arm3b_pairs.jsonl")
    i3b = load_jsonl(DATA_DIR / "arm3b_individual.jsonl")

    out_path = DATA_DIR / "arm3_scores.jsonl"
    done_models = set()
    existing = []
    if out_path.exists():
        existing = load_jsonl(out_path)
        done_models = {r["model"] for r in existing if r.get("kind") == "model_done"}
        if done_models:
            print("Resuming Arm 3; done models:", sorted(done_models), flush=True)

    all_rows = [r for r in existing if r["model"] in done_models]
    meta_path = OUT_DIR / "arm3_run_meta.json"
    run_meta = json.loads(meta_path.read_text()) if meta_path.exists() else {}

    for label, repo_id, rev, is_q3 in MODELS:
        if label not in selected_models or label in done_models:
            continue
        t0 = time.time()
        elig_col = ELIG_KEY[label]
        if label == "qwen3-4b-2507":
            # Frozen PLAN.md: exclude Qwen3-4B-2507 from Arm 3A aggregate (only 3 unique >= 2025-09-01 questions)
            p3a_elig = []
            i3a_elig = []
        else:
            p3a_elig = [r for r in p3a if r.get(elig_col)]
            i3a_elig = [r for r in i3a if r.get(elig_col)]
        total_items = len(p3a_elig) + len(i3a_elig) + len(p3b) + len(i3b)
        print(
            f"\n[Arm 3] Loading {label} (3a_pairs={len(p3a_elig)}, 3a_ind={len(i3a_elig)}, 3b_pairs={len(p3b)}, 3b_ind={len(i3b)}, total={total_items})...",
            flush=True,
        )

        model, tok, dev = load_judge(repo_id, rev)
        groups = build_token_groups(tok)
        m_rows = []
        item_counter = 0

        def tick():
            nonlocal item_counter
            item_counter += 1
            if item_counter % 50 == 0 or item_counter == total_items:
                print(f"  {label}: {item_counter}/{total_items} ({time.time()-t0:.1f}s)", flush=True)

        # 1. Arm 3A pairs (high forecast vs low forecast)
        for r in p3a_elig:
            m_rows.append({
                "model": label,
                "kind": "arm3a_pair",
                "id": r["id"],
                "resolved_to": r["resolved_to"],
                "more_accurate_side": r["more_accurate_side"],
                "strict_opposing": r["strict_opposing"],
                "inst_verbatim": swapped_ab(model, tok, dev, groups, is_q3, r["question"], r["high_text"], r["low_text"], "instructed"),
                "inst_redacted": swapped_ab(model, tok, dev, groups, is_q3, r["question"], r["high_text_redacted"], r["low_text_redacted"], "instructed"),
                "htv_redacted": swapped_ab(model, tok, dev, groups, is_q3, r["question"], r["high_text_redacted"], r["low_text_redacted"], "hard_to_vary"),
            })
            tick()

        # 2. Arm 3A individual
        for r in i3a_elig:
            iv, iv_m = score_single(model, tok, dev, groups, is_q3, r["question"], r["text"], "instructed")
            ir, ir_m = score_single(model, tok, dev, groups, is_q3, r["question"], r["text_redacted"], "instructed")
            hr, hr_m = score_single(model, tok, dev, groups, is_q3, r["question"], r["text_redacted"], "hard_to_vary")
            m_rows.append({
                "model": label,
                "kind": "arm3a_ind",
                "id": r["id"],
                "rationale_idx": r["rationale_idx"],
                "forecast": r["forecast"],
                "accuracy": r["accuracy"],
                "resolved_to": r["resolved_to"],
                "word_count": r["word_count"],
                "inst_verbatim": iv, "inst_verbatim_mass": iv_m,
                "inst_redacted": ir, "inst_redacted_mass": ir_m,
                "htv_redacted": hr, "htv_redacted_mass": hr_m,
            })
            tick()

        # 3. Arm 3B pairs (YES positioned vs NO positioned)
        for r in p3b:
            m_rows.append({
                "model": label,
                "kind": "arm3b_pair",
                "id": r["id"],
                "resolved_to": r["resolved_to"],
                "more_accurate_side": r["more_accurate_side"],
                "inst_verbatim": swapped_ab(model, tok, dev, groups, is_q3, r["question"], r["yes_text"], r["no_text"], "instructed"),
                "inst_redacted": swapped_ab(model, tok, dev, groups, is_q3, r["question"], r["yes_text_redacted"], r["no_text_redacted"], "instructed"),
                "htv_redacted": swapped_ab(model, tok, dev, groups, is_q3, r["question"], r["yes_text_redacted"], r["no_text_redacted"], "hard_to_vary"),
            })
            tick()

        # 4. Arm 3B individual
        for r in i3b:
            iv, iv_m = score_single(model, tok, dev, groups, is_q3, r["question"], r["text"], "instructed")
            ir, ir_m = score_single(model, tok, dev, groups, is_q3, r["question"], r["text_redacted"], "instructed")
            hr, hr_m = score_single(model, tok, dev, groups, is_q3, r["question"], r["text_redacted"], "hard_to_vary")
            m_rows.append({
                "model": label,
                "kind": "arm3b_ind",
                "id": r["id"],
                "comment_idx": r["comment_idx"],
                "comment_id": r["comment_id"],
                "position_outcome": r["position_outcome"],
                "resolved_to": r["resolved_to"],
                "word_count": r["word_count"],
                "inst_verbatim": iv, "inst_verbatim_mass": iv_m,
                "inst_redacted": ir, "inst_redacted_mass": ir_m,
                "htv_redacted": hr, "htv_redacted_mass": hr_m,
            })
            tick()

        m_rows.append({"model": label, "kind": "model_done"})
        unload_judge(model, dev)
        all_rows.extend(m_rows)
        atomic_write_jsonl(out_path, all_rows)
        run_meta[label] = {"wall_s": round(time.time() - t0, 1), "rows": len(m_rows) - 1}
        meta_path.write_text(json.dumps(run_meta, indent=2))
        print(f"  Saved Arm 3 for {label}: {run_meta[label]}", flush=True)

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


if __name__ == "__main__":
    main()
