"""Ask chat models who they are with 30 fixed prompts, save the raw replies, and count the claimed identities.

  uv run --no-config identity_test.py space --target ornith-1.5-122b-space --out runs/ornith.jsonl
  uv run --no-config identity_test.py kaggle-job --models llama-3.1-8b,glm-4-9b --out /tmp/job.py
  uv run --no-config identity_test.py count runs/*.jsonl --overrides overrides.json --out summary.json
"""

import argparse
import json
import sys
import time
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

from classify import LABELS, label, mentions

HERE = Path(__file__).parent
PROMPTS = json.loads((HERE / "prompts.json").read_text())["prompts"]

# Sampling for every local open-weight run: the general-task setting on the Ornith and Qwen3.5 model cards,
# applied to all local models so they are compared at one setting. A Space's sampling is whatever it serves.
SAMPLING = {"temperature": 1.0, "top_p": 0.95, "top_k": 0, "seed": 1234}

LOCAL_MODELS = {
    "ornith-1.5-9b": {"repo": "ornith-ai/Ornith-1.5-9B", "multimodal": True, "max_new_tokens": 4096, "batch": 10},
    "qwen3.5-9b": {"repo": "Qwen/Qwen3.5-9B", "multimodal": True, "max_new_tokens": 4096, "batch": 10},
    "llama-3.1-8b": {"repo": "unsloth/Llama-3.1-8B-Instruct", "max_new_tokens": 1024, "batch": 10},
    "deepseek-r1-distill-qwen-7b": {"repo": "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", "max_new_tokens": 4096,
                                    "batch": 10},
    "glm-4-9b": {"repo": "zai-org/GLM-4-9B-0414", "max_new_tokens": 1024, "batch": 10},
}


def ornith_space(client, text):
    """The Space's own two steps: add the user turn, then stream the reply. No system prompt in its code."""
    _, history = client.predict(text, [], api_name="/user_message")
    history = client.predict(history, api_name="/bot_message")
    parts = history[-1]["content"]
    return "".join(p.get("text", "") for p in parts) if isinstance(parts, list) else str(parts)


SPACES = {
    "ornith-1.5-122b-space": {
        "space": "ornith-ai/Ornith-1.5-122B", "model": "ornith-1.5-122b",
        "endpoint": "Hugging Face Space ornith-ai/Ornith-1.5-122B (forwards to the Ornith API)",
        "system_prompt": None, "params": "server default (the Space sets no sampling options)", "call": ornith_space,
    },
}


def now():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def selected(ids):
    if not ids:
        return PROMPTS
    wanted = ids.split(",")
    return [p for p in PROMPTS if p["id"] in wanted]


def cmd_space(args):
    from gradio_client import Client

    spec = SPACES[args.target]
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    with out.open("a") as fh:
        for prompt in selected(args.ids):
            row = {"ts": now(), "target": args.target, "model": spec["model"], "endpoint": spec["endpoint"],
                   "prompt_id": prompt["id"], "kind": prompt["kind"], "prompt": prompt["text"],
                   "system_prompt": spec["system_prompt"], "params": spec["params"], "run": args.run}
            started = time.time()
            try:
                # A new client per prompt gives a new session, so every prompt starts a fresh chat.
                row["reply"], row["error"] = spec["call"](Client(spec["space"], verbose=False), prompt["text"]), None
            except Exception as error:  # a failed call is logged as a row, never retried silently
                row["reply"], row["error"] = "", f"{type(error).__name__}: {error}"[:500]
            row["latency_s"] = round(time.time() - started, 2)
            fh.write(json.dumps(row, ensure_ascii=False) + "\n")
            fh.flush()
            print(f"{prompt['id']} {row['latency_s']}s {label(args.target, row['reply'])} {row['error'] or ''}")
            time.sleep(args.pause)
    return 0


def cmd_kaggle_job(args):
    # --ids reruns a subset; --max-time caps each batch's generate() call so a slow batch ends inside the session.
    extra = {"prompt_ids": args.ids.split(",") if args.ids else None, "max_time": args.max_time}
    models = [{"key": key, **LOCAL_MODELS[key], **extra} for key in args.models.split(",")]
    script = (HERE / "kaggle_job.py").read_text()
    # Each value goes in as a Python string literal of JSON, so JSON true/null never meet the Python parser.
    for name, value in (("__PROMPTS__", PROMPTS), ("__MODELS__", models), ("__SAMPLING__", SAMPLING)):
        script = script.replace(name, repr(json.dumps(value, ensure_ascii=False)))
    Path(args.out).write_text(script)
    print(f"wrote {args.out} for {[m['key'] for m in models]}")
    return 0


def load_rows(paths, run):
    rows = []
    for path in paths:
        for line in Path(path).read_text().splitlines():
            row = json.loads(line)
            if run is None or row.get("run", "main") == run:
                rows.append(row)
    return rows


def tally(rows, overrides):
    """Counts per target; an override from hand review replaces the automatic label and is counted.

    An override key is "<target>/<prompt id>" for the main run and "<target>/<prompt id>@<run>" for any other run.
    """
    table = {}
    for row in rows:
        target = row["target"]
        entry = table.setdefault(target, {"model": row["model"], "endpoint": row["endpoint"], "counts": Counter(),
                                          "n": 0, "errors": 0, "overridden": 0, "mentions": Counter(), "rows": []})
        auto = label(target, row["reply"]) if not row.get("error") else "error"
        run = row.get("run", "main")
        key = f"{target}/{row['prompt_id']}" + ("" if run == "main" else f"@{run}")
        override = overrides.get(key, {})
        final = override.get("label", auto)
        entry["overridden"] += final != auto
        entry["n"] += 1
        entry["errors"] += auto == "error"
        entry["counts"][final] += 1
        entry["mentions"].update(mentions(row["reply"] or ""))
        entry["rows"].append({"prompt_id": row["prompt_id"], "run": run, "auto": auto, "final": final,
                              **({"note": override["note"]} if "note" in override else {})})
    return table


def cmd_count(args):
    overrides = json.loads(Path(args.overrides).read_text()) if args.overrides else {}
    table = tally(load_rows(args.files, args.run), overrides)
    print(f"{'target':32} " + " ".join(f"{name:>6}" for name in LABELS) + "    n  over")
    for target, entry in table.items():
        cells = " ".join(f"{entry['counts'].get(name, 0):>6}" for name in LABELS)
        print(f"{target:32} {cells} {entry['n']:>4} {entry['overridden']:>5}")
    if args.out:
        Path(args.out).write_text(json.dumps(table, indent=2, default=dict, ensure_ascii=False))
    return 0


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest="cmd", required=True)
    space = sub.add_parser("space", help="send the prompts to a Gradio Space")
    space.add_argument("--target", required=True, choices=sorted(SPACES))
    space.add_argument("--out", required=True)
    space.add_argument("--ids", help="comma-separated prompt ids (default: all 30)")
    space.add_argument("--run", default="main", help="run label, e.g. main or rerun")
    space.add_argument("--pause", type=float, default=8.0, help="seconds between calls")
    job = sub.add_parser("kaggle-job", help="render the Kaggle job script for local open-weight models")
    job.add_argument("--models", required=True, help=",".join(LOCAL_MODELS))
    job.add_argument("--ids", help="comma-separated prompt ids (default: all 30)")
    job.add_argument("--max-time", type=float, help="seconds one batch may generate before it stops")
    job.add_argument("--out", required=True)
    count = sub.add_parser("count", help="label replies and print the table")
    count.add_argument("files", nargs="+")
    count.add_argument("--overrides")
    count.add_argument("--run", help="only rows with this run label")
    count.add_argument("--out")
    args = parser.parse_args(argv)
    return {"space": cmd_space, "kaggle-job": cmd_kaggle_job, "count": cmd_count}[args.cmd](args)


if __name__ == "__main__":
    sys.exit(main())
