#!/usr/bin/env python3
"""Pre-freeze dry run: fetch & pin ForecastBench/Manifold data and HF models,
audit exact candidate counts/cutoffs/comment timestamps, verify tokenizers on synthetic
prompts (computing zero verdict scores on real items), and verify reachability."""
import datetime
import gc
import hashlib
import json
import os
import re
import shutil
import time
import urllib.request
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np
import torch
from huggingface_hub import snapshot_download
from transformers import AutoModelForCausalLM, AutoTokenizer

ROOT = Path(__file__).resolve().parent.parent
DATA_RAW = ROOT / "data" / "raw"
DRYRUN_DIR = ROOT / "dryrun"
DATA_RAW.mkdir(parents=True, exist_ok=True)
DRYRUN_DIR.mkdir(parents=True, exist_ok=True)

FB_SHA = "86b92ba06ed34d606d633bff3e99af54dd447d3a"
FB_RAW = f"https://raw.githubusercontent.com/forecastingresearch/forecastbench-datasets/{FB_SHA}/datasets"

Q_ROUNDS_2026 = [
    "2026-01-04", "2026-01-18", "2026-02-01", "2026-02-15", "2026-03-01",
    "2026-03-15", "2026-03-29", "2026-04-12", "2026-04-26", "2026-05-10",
    "2026-05-24", "2026-06-07", "2026-06-21", "2026-07-05", "2026-07-19",
    "2026-08-02", "2026-08-16", "2026-08-30", "2026-09-13",
]
R_ROUNDS_2026 = Q_ROUNDS_2026 + ["2026-09-27", "2026-10-11", "2026-10-25"]

MODELS = [
    ("qwen2.5-1.5b", "Qwen/Qwen2.5-1.5B-Instruct", "989aa7980e4cf806f80c7fef2b1adb7bc71aa306"),
    ("smollm2-1.7b", "HuggingFaceTB/SmolLM2-1.7B-Instruct", "31b70e2e869a7173562077fd711b654946d38674"),
    ("qwen3-4b-2507", "Qwen/Qwen3-4B-Instruct-2507", "cdbee75f17c01a7cc42f958dc650907174af0554"),
]


def sha256_file(p: Path) -> str:
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def fetch_url(url: str, dest: Path) -> Path:
    if dest.exists() and dest.stat().st_size > 0:
        return dest
    dest.parent.mkdir(parents=True, exist_ok=True)
    req = urllib.request.Request(url, headers={"User-Agent": "judges-postcutoff-research/1.0"})
    with urllib.request.urlopen(req, timeout=30) as resp:
        data = resp.read()
    tmp = dest.with_suffix(dest.suffix + ".tmp")
    tmp.write_bytes(data)
    tmp.replace(dest)
    return dest


def extract_tiptap_text(node) -> str:
    if isinstance(node, str):
        return node
    if isinstance(node, dict):
        parts = []
        if "text" in node and isinstance(node["text"], str):
            parts.append(node["text"])
        for ch in node.get("content", []):
            t = extract_tiptap_text(ch)
            if t:
                parts.append(t)
        return " ".join(parts)
    if isinstance(node, list):
        return " ".join(extract_tiptap_text(x) for x in node)
    return ""


def clean_ws(s: str) -> str:
    return re.sub(r"\s+", " ", s or "").strip()


def parse_iso_ms(s: str):
    if not s:
        return None
    try:
        dt = datetime.datetime.fromisoformat(s.replace("Z", "+00:00"))
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=datetime.timezone.utc)
        return int(dt.timestamp() * 1000)
    except Exception:
        return None


def main():
    input_hashes = []

    # 1. Fetch ForecastBench 2026 question & resolution sets + 2024-07-21 superforecasters
    print("[1/5] Fetching ForecastBench pinned files at", FB_SHA)
    fb_dir = DATA_RAW / "forecastbench"
    for r in Q_ROUNDS_2026:
        p = fetch_url(f"{FB_RAW}/question_sets/{r}-llm.json", fb_dir / "question_sets" / f"{r}-llm.json")
        input_hashes.append((f"forecastbench/question_sets/{r}-llm.json", p.stat().st_size, sha256_file(p)))
    for r in R_ROUNDS_2026:
        p = fetch_url(f"{FB_RAW}/resolution_sets/{r}_resolution_set.json", fb_dir / "resolution_sets" / f"{r}_resolution_set.json")
        input_hashes.append((f"forecastbench/resolution_sets/{r}_resolution_set.json", p.stat().st_size, sha256_file(p)))

    for rel, url in [
        ("question_sets/2024-07-21-human.json", f"{FB_RAW}/question_sets/2024-07-21-human.json"),
        ("resolution_sets/2024-07-21_resolution_set.json", f"{FB_RAW}/resolution_sets/2024-07-21_resolution_set.json"),
        (
            "forecast_sets/2024-07-21.ForecastBench.human_super_individual.json",
            f"https://huggingface.co/datasets/forecastingresearch/forecastbench-datasets/resolve/{FB_SHA}/datasets/forecast_sets/2024-07-21/2024-07-21.ForecastBench.human_super_individual.json",
        ),
    ]:
        p = fetch_url(url, fb_dir / rel)
        input_hashes.append((f"forecastbench/{rel}", p.stat().st_size, sha256_file(p)))

    # 2. Audit Corpus-2026 market candidates (metadata only, NO model runs)
    print("[2/5] Auditing Corpus-2026 binary market candidates...")
    res_map = {}
    for r in R_ROUNDS_2026:
        d = json.loads((fb_dir / "resolution_sets" / f"{r}_resolution_set.json").read_text())
        for row in d.get("resolutions", d):
            qid = row.get("id")
            if isinstance(qid, str) and row.get("resolved") is True and row.get("resolved_to") in (0, 1, 0.0, 1.0):
                rdate = row.get("resolution_date") or ""
                if rdate >= "2026-01-01":
                    # keep earliest resolution record if multiple
                    if qid not in res_map or rdate < (res_map[qid].get("resolution_date") or "9999"):
                        res_map[qid] = row

    # Collect earliest question snapshot per id across 2026-01-04..2026-09-13
    q_earliest = {}
    for r in Q_ROUNDS_2026:
        d = json.loads((fb_dir / "question_sets" / f"{r}-llm.json").read_text())
        for q in d.get("questions", d):
            qid = q.get("id")
            if isinstance(qid, str) and qid not in q_earliest:
                q_copy = dict(q)
                q_copy["_round_date"] = r
                q_earliest[qid] = q_copy

    MARKET_SOURCES = {"manifold", "metaculus", "polymarket", "infer"}
    candidates_all_mkt = []
    candidates_nontrivial = []
    all_manifold_2026_ids = []
    for qid, q in q_earliest.items():
        if q.get("source") not in MARKET_SOURCES or qid not in res_map:
            continue
        r = res_map[qid]
        try:
            pmkt = float(q.get("freeze_datetime_value"))
        except Exception:
            continue
        if not (0.0 <= pmkt <= 1.0):
            continue
        item = {
            "id": qid,
            "source": q["source"],
            "round_date": q["_round_date"],
            "resolution_date": r["resolution_date"],
            "resolved_to": int(round(float(r["resolved_to"]))),
            "p_mkt": pmkt,
            "freeze_datetime": q.get("freeze_datetime"),
        }
        candidates_all_mkt.append(item)
        if q["source"] == "manifold":
            all_manifold_2026_ids.append(item)
        if 0.10 <= pmkt <= 0.90:
            candidates_nontrivial.append(item)

    by_src_nt = Counter(x["source"] for x in candidates_nontrivial)
    by_y_nt = Counter(x["resolved_to"] for x in candidates_nontrivial)
    print(f"  All resolved 2026 market questions: {len(candidates_all_mkt)}")
    print(f"  Non-trivial (0.10<=P_mkt<=0.90): {len(candidates_nontrivial)} | by source={dict(by_src_nt)} | by Y={dict(by_y_nt)}")

    # 3. Audit Arm 3A (2024-07-21 superforecasters)
    print("[3/5] Auditing Arm 3A (2024-07-21 superforecasters)...")
    q24 = json.loads((fb_dir / "question_sets" / "2024-07-21-human.json").read_text())["questions"]
    r24 = json.loads((fb_dir / "resolution_sets" / "2024-07-21_resolution_set.json").read_text())["resolutions"]
    sf24 = json.loads((fb_dir / "forecast_sets" / "2024-07-21.ForecastBench.human_super_individual.json").read_text())["forecasts"]

    # Include any resolution from 2024-07-21_resolution_set OR 2025/2026 resolution sets? Let's check 2024-07-21 first
    r24_map = {}
    for row in r24:
        if isinstance(row.get("id"), str) and row.get("resolved") is True and row.get("resolved_to") in (0, 1, 0.0, 1.0):
            r24_map[(row["id"], row.get("resolution_date"))] = row

    sf_by_q = defaultdict(list)
    for f in sf24:
        if isinstance(f.get("id"), str) and isinstance(f.get("reasoning"), str) and len(clean_ws(f["reasoning"])) >= 80 and f.get("forecast") is not None:
            sf_by_q[(f["id"], f.get("resolution_date"))].append(f)

    # Check both matched keys and market-question fallback (resolution_date is None in forecast)
    r24_dates = []
    arm3a_stats = {}
    for cutoff in ["2024-10-01", "2024-12-01", "2025-09-01"]:
        n_q_rat = 0
        n_rat = 0
        n_opp = 0
        for k, flist in sf_by_q.items():
            r = r24_map.get(k)
            if r is None and k[1] is None:
                cands = [v for (qid, _rd), v in r24_map.items() if qid == k[0]]
                r = cands[0] if cands else None
            if r is None:
                continue
            rdate = r.get("resolution_date") or ""
            if rdate < cutoff:
                continue
            r24_dates.append(rdate)
            n_q_rat += 1
            n_rat += len(flist)
            hi = [x for x in flist if float(x["forecast"]) >= 0.60]
            lo = [x for x in flist if float(x["forecast"]) <= 0.40]
            if hi and lo:
                n_opp += 1
        arm3a_stats[cutoff] = {"questions_with_rationales": n_q_rat, "total_rationales": n_rat, "opposing_pairs": n_opp}
    print("  Arm 3A stats by resolution_date cutoff:", json.dumps(arm3a_stats))

    # 4. Audit Arm 3B (Manifold 2026 pre-resolution comments)
    print(f"[4/5] Auditing Arm 3B (Manifold pre-res comments across {len(all_manifold_2026_ids)} 2026 Manifold questions)...")
    mc_dir = DATA_RAW / "manifold_comments"
    mm_dir = DATA_RAW / "manifold_markets"
    mc_dir.mkdir(parents=True, exist_ok=True)
    mm_dir.mkdir(parents=True, exist_ok=True)

    m_with_2plus_pre = 0
    m_with_2plus_nt = 0
    m_total_pre_comments = 0
    for item in all_manifold_2026_ids:
        qid = item["id"]
        cpath = mc_dir / f"{qid}.json"
        mpath = mm_dir / f"{qid}.json"
        try:
            if not cpath.exists():
                fetch_url(f"https://api.manifold.markets/v0/comments?contractId={qid}&limit=100", cpath)
                time.sleep(0.05)
            if not mpath.exists():
                fetch_url(f"https://api.manifold.markets/v0/market/{qid}", mpath)
                time.sleep(0.05)
            cs = json.loads(cpath.read_text())
            mk = json.loads(mpath.read_text())
        except Exception as e:
            print(f"  Manifold fetch warn {qid}: {e}")
            continue
        res_ms = mk.get("resolutionTime")
        freeze_ms = parse_iso_ms(item["freeze_datetime"])
        if res_ms is None:
            res_ms = parse_iso_ms(item["resolution_date"] + "T00:00:00+00:00")
        cutoff_ms = min(freeze_ms or res_ms, res_ms - 7 * 86400 * 1000)
        pre_subst = []
        for c in cs:
            if c.get("commentType") == "contract" and c.get("createdTime", 10**18) < cutoff_ms:
                txt = clean_ws(extract_tiptap_text(c.get("content", "")))
                if len(txt) >= 100:
                    pre_subst.append(txt)
        if len(pre_subst) >= 2:
            m_with_2plus_pre += 1
            m_total_pre_comments += len(pre_subst)
            if 0.10 <= item["p_mkt"] <= 0.90:
                m_with_2plus_nt += 1
    print(f"  Manifold 2026 with >=2 pre-res comments (>=100 chars): {m_with_2plus_pre} (non-trivial P_mkt: {m_with_2plus_nt}), total pre-res comments={m_total_pre_comments}")

    # 5. Check disk, download models if needed, and run synthetic 10-item tokenizer dry run
    print("[5/5] Checking disk, pinning models, and running 10-item synthetic tokenizer check...")
    usage = shutil.disk_usage(Path.home())
    free_gb = usage.free / (1024 ** 3)
    print(f"  Free disk before downloads: {free_gb:.2f} GB")

    model_dryrun = {}
    synthetic_prompts = [
        ("yesno", "Question: Will a fair standard six-sided die roll a number greater than 3?\nWill the answer be Yes? Reply with only 'Yes' or 'No'."),
        ("yesno", "Question: Will a fair standard six-sided die roll a number greater than 3?\nWill the answer be No? Reply with only 'Yes' or 'No'."),
        ("ab", "Which argument gives stronger epistemic support?\n\nArgument A: Ten independent stations recorded 120 measurements using calibrated instruments.\nArgument B: Someone online felt sure it was true.\n\nReply with only 'A' or 'B'."),
        ("score", "Rate the epistemic strength of this argument from 1 (weakest) to 5 (strongest).\n\nArgument: Three independent clinical trials measured a 15% reduction.\n\nReply with only a single digit from 1 to 5."),
    ]

    for label, mid, rev in MODELS:
        usage_now = shutil.disk_usage(Path.home()).free / (1024 ** 3)
        print(f"  Loading/downloading {mid}@{rev[:10]} (free disk={usage_now:.2f} GB)...")
        if usage_now < 16.0 and label == "qwen3-4b-2507":
            raise RuntimeError(f"Low disk ({usage_now:.2f} GB) before {mid}; check fallback!")
        snap_dir = Path(snapshot_download(
            repo_id=mid,
            revision=rev,
            allow_patterns=["*.safetensors", "*.json", "*.txt", "*.model", "*.jinja"],
            ignore_patterns=["onnx/*", "onnx/**", "gguf/*", "gguf/**"],
        ))
        for fp in sorted(snap_dir.iterdir()):
            if fp.is_file():
                input_hashes.append((f"hf/{label}/{fp.name}", fp.stat().st_size, sha256_file(fp)))

        tok = AutoTokenizer.from_pretrained(str(snap_dir), local_files_only=True)
        dev = "mps" if torch.backends.mps.is_available() else "cpu"
        dtype = torch.float16 if dev == "mps" else torch.float32
        t0 = time.time()
        m = AutoModelForCausalLM.from_pretrained(str(snap_dir), dtype=dtype, local_files_only=True).to(dev).eval()
        load_s = time.time() - t0

        # Inspect single-token IDs for variants
        def tok_ids(cands):
            out = {}
            for s in cands:
                ids = tok.encode(s, add_special_tokens=False)
                out[s] = ids
            return out

        id_map = {
            "yesno": tok_ids(["Yes", " Yes", "yes", "No", " No", "no"]),
            "ab": tok_ids(["A", " A", "B", " B"]),
            "score": tok_ids(["1", "2", "3", "4", "5", " 1", " 2", " 3", " 4", " 5"]),
        }

        probe_checks = []
        t_inf0 = time.time()
        for kind, prompt in synthetic_prompts:
            kwargs = {"tokenize": False, "add_generation_prompt": True}
            if "qwen3" in label:
                kwargs["enable_thinking"] = False
            try:
                text = tok.apply_chat_template([{"role": "user", "content": prompt}], **kwargs)
            except TypeError:
                text = tok.apply_chat_template([{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True)
            inp = tok(text, return_tensors="pt", add_special_tokens=False).to(dev)
            with torch.no_grad():
                logits = m(**inp).logits[0, -1].float().cpu()
            probs = torch.softmax(logits, dim=-1)
            top5 = torch.topk(probs, 5)
            top5_fmt = [(tok.decode([i]), int(i), round(float(p), 4)) for i, p in zip(top5.indices.tolist(), top5.values.tolist())]

            if kind == "yesno":
                valid_strs = ["Yes", " Yes", "yes", "No", " No", "no"]
            elif kind == "ab":
                valid_strs = ["A", " A", "B", " B"]
            else:
                valid_strs = ["1", "2", "3", "4", "5", " 1", " 2", " 3", " 4", " 5"]
            valid_ids = {tok.encode(s, add_special_tokens=False)[0] for s in valid_strs if len(tok.encode(s, add_special_tokens=False)) == 1}
            valid_mass = float(probs[list(valid_ids)].sum())
            probe_checks.append({"kind": kind, "valid_mass": round(valid_mass, 4), "top5": top5_fmt})

        if dev == "mps":
            torch.mps.synchronize()
        inf_s = time.time() - t_inf0
        model_dryrun[label] = {
            "repo_id": mid,
            "revision": rev,
            "device": dev,
            "load_s": round(load_s, 2),
            "4_prompts_s": round(inf_s, 3),
            "token_ids": id_map,
            "synthetic_checks": probe_checks,
        }
        print(f"  {label}: load={load_s:.2f}s, 4_prompts={inf_s:.3f}s, valid_masses={[c['valid_mass'] for c in probe_checks]}")
        del m
        gc.collect()
        if dev == "mps":
            torch.mps.empty_cache()

    # Write INPUTS_sha256.txt and dryrun summary
    with open(ROOT / "INPUTS_sha256.txt", "w") as f:
        f.write(f"# ForecastBench datasets commit: {FB_SHA}\n")
        for name, sz, h in input_hashes:
            f.write(f"{h}  {sz}  {name}\n")

    summary = {
        "fb_sha": FB_SHA,
        "corpus_2026_all_market_resolved": len(candidates_all_mkt),
        "corpus_2026_nontrivial_count": len(candidates_nontrivial),
        "corpus_2026_nontrivial_by_source": dict(by_src_nt),
        "corpus_2026_nontrivial_by_y": dict(by_y_nt),
        "arm3a_stats": arm3a_stats,
        "arm3b_manifold_2plus_preres": m_with_2plus_pre,
        "arm3b_manifold_2plus_preres_nontrivial": m_with_2plus_nt,
        "arm3b_total_preres_comments": m_total_pre_comments,
        "models": model_dryrun,
        "free_disk_gb_after": round(shutil.disk_usage(Path.home()).free / (1024 ** 3), 2),
    }
    (DRYRUN_DIR / "audit.json").write_text(json.dumps(summary, indent=2))
    print("\nDRYRUN SUMMARY WRITTEN:", DRYRUN_DIR / "audit.json")
    print(json.dumps({k: v for k, v in summary.items() if k != "models"}, indent=2))


if __name__ == "__main__":
    main()
