"""Kaggle GPU job: run the fixed identity prompts on open-weight models, one fresh chat per prompt.

identity_test.py fills in PROMPTS, MODELS and SAMPLING before the push, so the job needs no staged dataset.
Each model downloads from the Hugging Face Hub (internet on), runs in fp16 across the session's GPUs,
writes /kaggle/working/<key>.jsonl, and its cache is deleted before the next model starts.
"""

import gc
import json
import shutil
import sys
import time
import traceback
from datetime import datetime, timezone
from pathlib import Path

PROMPTS = json.loads(__PROMPTS__)
MODELS = json.loads(__MODELS__)
SAMPLING = json.loads(__SAMPLING__)

OUT = Path("/kaggle/working")
CACHE = Path("/tmp/hf-cache")


def setup():
    import subprocess

    subprocess.run(
        [sys.executable, "-m", "pip", "install", "-q", "-U", "transformers>=5.8.1", "accelerate", "huggingface_hub"],
        check=True,
    )
    import torch

    assert torch.cuda.is_available(), "no GPU in this session"
    gpus = [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())]
    print(f"GPU_READY {gpus} torch={torch.__version__} py={sys.version.split()[0]}", flush=True)
    return gpus


def load(spec):
    import torch
    from huggingface_hub import snapshot_download
    from transformers import AutoModelForCausalLM, AutoModelForImageTextToText, AutoTokenizer

    path = snapshot_download(spec["repo"], revision=spec.get("revision"), cache_dir=CACHE,
                             allow_patterns=["*.json", "*.safetensors", "*.jinja", "*.txt", "*.model", "*.py"])
    tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
    tokenizer.padding_side = "left"
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    loader = AutoModelForImageTextToText if spec.get("multimodal") else AutoModelForCausalLM
    model = loader.from_pretrained(path, dtype=torch.float16, device_map="auto", trust_remote_code=True)
    model.eval()
    return tokenizer, model


def render(tokenizer, text):
    # No system message: the chat template's own default (if any) is what a plain local user gets.
    return tokenizer.apply_chat_template([{"role": "user", "content": text}], tokenize=False, add_generation_prompt=True)


def split_reasoning(decoded, prompt_text):
    """Return (reasoning, answer). Templates that open <think> in the prompt leave only </think> in the output."""
    opened_in_prompt = prompt_text.rstrip().endswith("<think>")
    if "</think>" in decoded:
        head, tail = decoded.split("</think>", 1)
        return head.replace("<think>", "").strip(), tail.strip()
    if opened_in_prompt or decoded.lstrip().startswith("<think>"):
        return decoded.replace("<think>", "").strip(), ""
    return "", decoded.strip()


def generate_batch(tokenizer, model, spec, batch):
    import torch

    rendered = [render(tokenizer, p["text"]) for p in batch]
    inputs = tokenizer(rendered, return_tensors="pt", padding=True, add_special_tokens=False).to(model.device)
    torch.manual_seed(SAMPLING["seed"])
    started = time.time()
    with torch.no_grad():
        output = model.generate(
            **inputs, do_sample=True, temperature=SAMPLING["temperature"], top_p=SAMPLING["top_p"],
            top_k=SAMPLING["top_k"], repetition_penalty=1.0, max_new_tokens=spec["max_new_tokens"],
            max_time=spec.get("max_time"), pad_token_id=tokenizer.pad_token_id,
        )
    seconds = round(time.time() - started, 1)
    new_tokens = output[:, inputs["input_ids"].shape[1]:]
    return rendered, new_tokens, seconds


def record(spec, prompt, rendered, token_ids, tokenizer, seconds, stops):
    decoded = tokenizer.decode(token_ids, skip_special_tokens=True)
    reasoning, answer = split_reasoning(decoded, rendered)
    used = int((token_ids != tokenizer.pad_token_id).sum())
    # A reply that never closed its turn hit the token cap or the batch time cap.
    ended = bool(stops & set(token_ids.tolist()))
    return {
        "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "target": spec["key"], "model": spec["repo"], "endpoint": "local open weights (transformers, Kaggle GPU)",
        "prompt_id": prompt["id"], "kind": prompt["kind"], "prompt": prompt["text"], "system_prompt": None,
        "params": {**SAMPLING, "max_new_tokens": spec["max_new_tokens"], "max_time_s": spec.get("max_time"),
                   "dtype": "float16"},
        "reply": answer, "reasoning": reasoning, "new_tokens": used,
        "truncated": used >= spec["max_new_tokens"] or not ended, "batch_seconds": seconds, "error": None,
    }


def run_model(spec, log):
    tokenizer, model = load(spec)
    log["rendered_example"][spec["key"]] = render(tokenizer, PROMPTS[0]["text"])
    # Where the layers landed: a layer offloaded to the CPU makes a batch many times slower.
    log.setdefault("devices", {})[spec["key"]] = sorted({str(d) for d in getattr(model, "hf_device_map", {}).values()})
    print(f"{spec['key']} devices {log['devices'][spec['key']]}", flush=True)
    eos = model.generation_config.eos_token_id
    stops = {tokenizer.pad_token_id, *(eos if isinstance(eos, list) else [eos])}
    prompts = [p for p in PROMPTS if not spec.get("prompt_ids") or p["id"] in spec["prompt_ids"]]
    out = OUT / f"{spec['key']}.jsonl"
    with out.open("w") as fh:
        for start in range(0, len(prompts), spec["batch"]):
            batch = prompts[start:start + spec["batch"]]
            rendered, new_tokens, seconds = generate_batch(tokenizer, model, spec, batch)
            for prompt, text, ids in zip(batch, rendered, new_tokens):
                fh.write(json.dumps(record(spec, prompt, text, ids, tokenizer, seconds, stops), ensure_ascii=False) + "\n")
            fh.flush()
            print(f"{spec['key']}: {start + len(batch)}/{len(prompts)} in {seconds}s", flush=True)
    del model
    gc.collect()


def main():
    gpus = setup()
    # Imported after setup() so the upgraded transformers is the one that loads.
    import torch
    import transformers

    log = {"started": datetime.now(timezone.utc).isoformat(timespec="seconds"), "gpus": gpus,
           "torch": torch.__version__, "transformers": transformers.__version__, "sampling": SAMPLING,
           "rendered_example": {}, "models": {}}
    for spec in MODELS:
        started = time.time()
        try:
            run_model(spec, log)
            log["models"][spec["key"]] = {"ok": True, "seconds": round(time.time() - started)}
        except Exception as error:  # one model failing must not lose the others' results
            traceback.print_exc()
            log["models"][spec["key"]] = {"ok": False, "error": f"{type(error).__name__}: {error}"[:500]}
        torch.cuda.empty_cache()
        shutil.rmtree(CACHE, ignore_errors=True)
        (OUT / "job-log.json").write_text(json.dumps(log, indent=2, ensure_ascii=False))
    print("done", json.dumps(log["models"]), flush=True)


main()
