#!/usr/bin/env python3
"""score_hf_mps.py: Offline local HuggingFace snapshot single-token Yes/No judge runner (MPS/CPU).

Supports `--prepare-only` (D-063 token-length & chat-template gate with zero forward passes)
and scored inference gated on a frozen `INPUT_MANIFEST.json` SHA256.

Computes exact full-vocabulary float64 softmax over the final prompt position (`omitted_mass = 0.0`),
summing exact probabilities over all vocabulary tokens whose `decode([tid]).strip().lower()` is
`"yes"` or `"no"`, plus greedy top-1 generated token decision (`yes` / `no` / `other`).
Raw prompt texts are read from `--private-inputs` (scratch) and NEVER written to tracked outputs.

Author: Gemini 4 Carbon (High), 2026-11-23 (tracker #57, #77).
"""
from __future__ import annotations

import argparse
import datetime
import hashlib
import json
import random
import time
from pathlib import Path
from typing import Any, Dict, List

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL_SPECS = {
    "M1_qwen25_1p5b": {
        "repo": "Qwen/Qwen2.5-1.5B-Instruct",
        "snapshot_subdir": "models--Qwen--Qwen2.5-1.5B-Instruct/snapshots/989aa7980e4cf806f80c7fef2b1adb7bc71aa306",
        "params_b": 1.54,
    },
    "M2_smollm2_1p7b": {
        "repo": "HuggingFaceTB/SmolLM2-1.7B-Instruct",
        "snapshot_subdir": "models--HuggingFaceTB--SmolLM2-1.7B-Instruct/snapshots/31b70e2e869a7173562077fd711b654946d38674",
        "params_b": 1.71,
    },
    "M3_qwen3_4b": {
        "repo": "Qwen/Qwen3-4B-Instruct-2507",
        "snapshot_subdir": "models--Qwen--Qwen3-4B-Instruct-2507/snapshots/cdbee75f17c01a7cc42f958dc650907174af0554",
        "params_b": 4.02,
    },
}


def sha256_bytes(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def sha256_str(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def measurement_diff(a: Dict[str, Any], b: Dict[str, Any]) -> float:
    assert a["generated_decision"] == b["generated_decision"], (
        f"Identity decision drift: {a['generated_decision']} vs {b['generated_decision']}"
    )
    return max(
        abs(a["p_yes_observed"] - b["p_yes_observed"]),
        abs(a["p_no_observed"] - b["p_no_observed"]),
        abs(a["conditional_yes_interval"][0] - b["conditional_yes_interval"][0]),
        abs(a["conditional_yes_interval"][1] - b["conditional_yes_interval"][1]),
    )


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--judge", choices=sorted(MODEL_SPECS.keys()), required=True)
    ap.add_argument("--hf-hub-cache", default=str(Path.home() / ".cache" / "huggingface" / "hub"))
    ap.add_argument("--private-inputs", required=True)
    ap.add_argument("--manifest", required=True)
    ap.add_argument("--out-json", required=True)
    ap.add_argument("--device", choices=["auto", "mps", "cpu"], default="auto")
    ap.add_argument("--max-tokens", type=int, default=4080)
    ap.add_argument("--prepare-only", action="store_true")
    ap.add_argument("--freeze-manifest-sha256", default="")
    args = ap.parse_args()

    spec = MODEL_SPECS[args.judge]
    snap_path = Path(args.hf_hub_cache) / spec["snapshot_subdir"]
    assert snap_path.exists(), f"Missing local snapshot: {snap_path}"

    priv_bytes = Path(args.private_inputs).read_bytes()
    man_bytes = Path(args.manifest).read_bytes()
    man = json.loads(man_bytes)
    assert sha256_bytes(priv_bytes) == man["private_payload_sha256"], "Private payload SHA256 mismatch with manifest"

    payload = json.loads(priv_bytes)
    items: List[Dict[str, Any]] = payload["items"]
    assert len(items) == 720

    tok = AutoTokenizer.from_pretrained(str(snap_path), local_files_only=True)
    yes_ids = [i for i in range(len(tok)) if tok.decode([i]).strip().lower() == "yes"]
    no_ids = [i for i in range(len(tok)) if tok.decode([i]).strip().lower() == "no"]
    assert yes_ids and no_ids, "Missing Yes/No token IDs in vocabulary"

    rendered_by_id: Dict[str, Dict[str, Any]] = {}
    max_tok_seen = 0
    for it in items:
        rendered = tok.apply_chat_template(
            [{"role": "user", "content": it["content"]}],
            tokenize=False,
            add_generation_prompt=True,
        )
        t_ids = tok.encode(rendered, add_special_tokens=False)
        n_tok = len(t_ids)
        assert n_tok <= args.max_tokens, f"Token limit exceeded on {it['item_id']}: {n_tok} > {args.max_tokens}"
        max_tok_seen = max(max_tok_seen, n_tok)
        rendered_by_id[it["item_id"]] = {
            "item": it,
            "input_ids": t_ids,
            "n_tokens": n_tok,
            "rendered_sha256": sha256_str(rendered),
            "tokens_sha256": sha256_str(json.dumps(t_ids, separators=(",", ":"))),
        }

    if args.prepare_only:
        gate_out = {
            "judge": args.judge,
            "repo": spec["repo"],
            "snapshot_revision": snap_path.name,
            "prepare_only": True,
            "context_gate_pass": True,
            "n_items": len(items),
            "max_tokens": max_tok_seen,
            "n_yes_vocab_ids": len(yes_ids),
            "n_no_vocab_ids": len(no_ids),
            "scored_calls": 0,
        }
        out_p = Path(args.out_json)
        out_p.parent.mkdir(parents=True, exist_ok=True)
        out_p.write_text(json.dumps(gate_out, indent=2, sort_keys=True) + "\n")
        print(json.dumps(gate_out, indent=2))
        return

    assert args.freeze_manifest_sha256, "Scored run requires --freeze-manifest-sha256"
    assert sha256_bytes(man_bytes) == args.freeze_manifest_sha256, "Manifest drifted from frozen SHA256"

    out_p = Path(args.out_json)
    assert not out_p.exists(), f"Refusing to overwrite scored output {out_p}"

    dev = (
        "mps" if (args.device == "auto" and torch.backends.mps.is_available())
        else ("cpu" if args.device == "auto" else args.device)
    )
    dtype = torch.bfloat16 if dev == "mps" else torch.float32
    t_load0 = time.monotonic()
    model = AutoModelForCausalLM.from_pretrained(
        str(snap_path),
        local_files_only=True,
        dtype=dtype,
    ).to(dev)
    model.eval()
    load_sec = time.monotonic() - t_load0

    yes_idx_t = torch.tensor(yes_ids, dtype=torch.long, device="cpu")
    no_idx_t = torch.tensor(no_ids, dtype=torch.long, device="cpu")

    calls = 0

    @torch.no_grad()
    def score_one(item_id: str) -> Dict[str, Any]:
        nonlocal calls
        rec = rendered_by_id[item_id]
        t0 = time.monotonic()
        inp = torch.tensor([rec["input_ids"]], dtype=torch.long, device=dev)
        logits = model(input_ids=inp, use_cache=False).logits[0, -1, :].detach().to("cpu").to(torch.float64)
        if dev == "mps":
            torch.mps.synchronize()
        elapsed = time.monotonic() - t0
        calls += 1

        # Exact full-vocabulary softmax in float64 (cancellation-safe via max shift)
        probs = torch.softmax(logits - logits.max(), dim=-1)
        py = float(probs[yes_idx_t].sum().item())
        pn = float(probs[no_idx_t].sum().item())
        den = py + pn
        cond_y = py / den if den > 0.0 else 0.5
        log_odds = float(torch.log(torch.tensor(max(py, 1e-300) / max(pn, 1e-300))).item())
        top_id = int(torch.argmax(logits).item())
        top_str = tok.decode([top_id])
        top_clean = top_str.strip().lower()
        decision = top_clean if top_clean in ("yes", "no") else "other"

        it = rec["item"]
        return {
            "item_id": item_id,
            "component": it["component"],
            "slice": it["slice"],
            "prompt_id": it["prompt_id"],
            "completion_idx": it["completion_idx"],
            "gold": it["gold"],
            "arm": it["arm"],
            "n_tokens": rec["n_tokens"],
            "content_sha256": it["content_sha256"],
            "rendered_sha256": rec["rendered_sha256"],
            "tokens_sha256": rec["tokens_sha256"],
            "p_yes_observed": py,
            "p_no_observed": pn,
            "returned_mass": 1.0,
            "omitted_mass": 0.0,
            "conditional_yes_interval": [cond_y, cond_y],
            "cond_p_yes": cond_y,
            "log_odds_yes_no": log_odds,
            "censored_missing_class": False,
            "generated_decision": decision,
            "top_token_id": top_id,
            "elapsed_sec": elapsed,
        }

    # 1. Identity controls (8 items x 2 repeats = 16 calls)
    id_controls = []
    max_id_diff = 0.0
    for cid in payload["identity_control_item_ids"]:
        r0 = score_one(cid)
        r1 = score_one(cid)
        diff = measurement_diff(r0, r1)
        max_id_diff = max(max_id_diff, diff)
        assert diff <= 1e-4, f"Identity gate failed on {cid}: {diff}"
        id_controls.append({"item_id": cid, "max_diff": diff})

    # 2. Seeded main schedule (720 items)
    rng = random.Random(20261123)
    schedule = [it["item_id"] for it in items]
    rng.shuffle(schedule)

    results_by_id: Dict[str, Dict[str, Any]] = {}
    t_main0 = time.monotonic()
    for idx, iid in enumerate(schedule, 1):
        results_by_id[iid] = score_one(iid)
        if idx % 120 == 0 or idx == len(schedule):
            print(json.dumps({
                "judge": args.judge,
                "device": dev,
                "completed_main": idx,
                "total_main": len(schedule),
                "elapsed_sec": round(time.monotonic() - t_main0, 2),
            }), flush=True)

    assert calls == 736
    ordered_rows = [results_by_id[it["item_id"]] for it in items]
    out_doc = {
        "schema_version": 1,
        "judge": args.judge,
        "repo": spec["repo"],
        "snapshot_revision": snap_path.name,
        "params_b": spec["params_b"],
        "runtime": f"transformers-{dev}-{dtype}",
        "manifest_sha256": sha256_bytes(man_bytes),
        "private_payload_sha256": man["private_payload_sha256"],
        "load_sec": load_sec,
        "main_wall_sec": time.monotonic() - t_main0,
        "scored_calls": calls,
        "main_calls": 720,
        "identity_calls": 16,
        "identity_gate_pass": True,
        "identity_max_diff": max_id_diff,
        "identity_controls": id_controls,
        "completed_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "rows": ordered_rows,
    }
    out_p.parent.mkdir(parents=True, exist_ok=True)
    out_p.write_text(json.dumps(out_doc, indent=2, sort_keys=True) + "\n")
    print(json.dumps({
        "status": "DONE",
        "judge": args.judge,
        "scored_calls": calls,
        "identity_max_diff": max_id_diff,
        "main_wall_sec": round(out_doc["main_wall_sec"], 2),
    }, indent=2))


if __name__ == "__main__":
    main()
