"""One question or the questions behind it? Benchmark on public data.

Usage: bench.py <task> <method> [limit]
  task:   tickets | civil
  method: dm1 dm5 (OTel-2.0-Decision on one L40S), mimo1 mimo5 (MiMo-V2.6-Flash),
          opus1 opus5 (Claude Opus 5.5 through the Claude Code CLI)
Writes results/<task>-<method>.jsonl, one line per item, resumable.

The questions and rules below were written before any run and are not tuned on the data.
"""
import json, math, os, subprocess, sys, time, urllib.request
from concurrent.futures import ThreadPoolExecutor

URL = os.environ["OPENAI_BASE_URL"].rstrip("/") + "/chat/completions"  # any OpenAI-compatible endpoint
KEY = os.environ.get("OPENAI_API_KEY", "")
DM, MIMO, OPUS = os.environ.get("DECISION_MODEL", "otel-decision-26b-a4b"), os.environ.get("LARGE_MODEL", "mimo"), "claude-opus-5-5"

TASKS = {
    "tickets": {
        "data": "data/tickets600.json", "noun": "Ticket",
        "one": "Is this support ticket urgent?",
        "checks": {
            "outage": "Is a production or customer-facing service down or badly degraded right now?",
            "data": "Does it involve possible data loss, data corruption, or a security exposure?",
            "blocked": "Is the customer blocked from their work with no workaround?",
            "breadth": "Does it affect many users, or a revenue-critical workflow?",
            "deadline": "Does the ticket state a concrete deadline or time pressure that is near?",
        },
        "rule": lambda a: a["outage"] or a["data"] or (a["blocked"] and (a["breadth"] or a["deadline"])),
    },
    "civil": {
        "data": "data/civil600.json", "noun": "Comment",
        "one": "Is this comment toxic, meaning rude, disrespectful, or unreasonable in a way likely to make someone leave a discussion?",
        "checks": {
            "insult": "Does the comment insult or demean a person or group?",
            "threat": "Does it threaten or wish violence or harm on someone?",
            "obscene": "Does it use obscene, profane or vulgar language?",
            "identity": "Does it attack or demean people based on identity, such as race, religion, gender, nationality or sexuality?",
            "hostile": "Is its tone hostile, contemptuous or mocking toward someone?",
        },
        "rule": lambda a: any(a.values()),
    },
    "sms": {
        "data": "data/sms600.json", "noun": "Text message",
        "one": "Is this text message spam?",
        "checks": {
            "prize": "Does it claim the recipient won a prize, cash, or a free gift?",
            "action": "Does it urge the recipient to call, text, or reply to a number or short code?",
            "promo": "Is it advertising a product, service, offer, or subscription?",
            "link": "Does it ask the recipient to visit a website or link?",
            "personal": "Is it a personal message between people who know each other?",
        },
        "rule": lambda a: (not a["personal"]) and (a["prize"] or a["action"] or a["promo"] or a["link"]),
    },
}


def prompt(noun, text, q):
    # Item first, question last: every question about one item shares a prefix the engine caches.
    return f"{noun}:\n{text}\n\n{q} Answer Yes or No."


def ask_pool(model, content, thinking_off=False):
    body = {"model": model, "max_tokens": 1, "temperature": 0, "logprobs": True, "top_logprobs": 10,
            "messages": [{"role": "user", "content": content}]}
    if thinking_off:
        body["chat_template_kwargs"] = {"enable_thinking": False}
    req = urllib.request.Request(URL, data=json.dumps(body).encode(), headers={
        "Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
    for attempt in range(6):
        try:
            t = time.time()
            r = json.load(urllib.request.urlopen(req, timeout=180))
            s = time.time() - t
            break
        except Exception:
            time.sleep(2 * (attempt + 1))
    else:
        raise RuntimeError("request failed")
    p = {}
    for c in r["choices"][0]["logprobs"]["content"][0]["top_logprobs"]:
        w = c["token"].strip().strip("*").lower()
        if w in ("yes", "no"):
            p[w] = p.get(w, 0) + math.exp(c["logprob"])
    yes = p.get("yes", 0) / ((p.get("yes", 0) + p.get("no", 0)) or 1)
    u = r["usage"]
    return {"p": yes, "s": s, "in": u["prompt_tokens"], "out": u["completion_tokens"]}


def ask_opus(content, system):
    cmd = ["claude", "-p", "--model", OPUS, "--effort", "low", "--tools", "", "--system-prompt", system,
           "--no-session-persistence", "--strict-mcp-config", "--output-format", "json"]
    for attempt in range(6):
        try:
            out = subprocess.run(cmd, input=content, capture_output=True, text=True, timeout=300, cwd="/tmp")
            d = json.loads(out.stdout)
            if d.get("is_error"):
                raise RuntimeError(d.get("result"))
            u = d["usage"]
            return {"text": d["result"].strip(), "s": d["duration_api_ms"] / 1000,
                    "in": u["input_tokens"] + u["cache_creation_input_tokens"] + u["cache_read_input_tokens"],
                    "out": u["output_tokens"]}
        except Exception as e:
            err = e
            time.sleep(10 * (attempt + 1))
    raise RuntimeError(f"opus failed: {err}")


def run_item(task, method, item):
    T = TASKS[task]
    if method in ("dm1", "mimo1"):
        r = ask_pool(DM if method == "dm1" else MIMO, prompt(T["noun"], item["text"], T["one"]), method == "mimo1")
        return {"pred": r["p"] >= 0.5, "score": r["p"], "s": r["s"], "in": r["in"], "out": r["out"], "calls": 1}
    if method in ("dm5", "mimo5"):
        model = DM if method == "dm5" else MIMO
        with ThreadPoolExecutor(len(T["checks"])) as ex:
            rs = dict(zip(T["checks"], ex.map(lambda q: ask_pool(model, prompt(T["noun"], item["text"], q), method == "mimo5"),
                                               T["checks"].values())))
        a = {k: v["p"] >= 0.5 for k, v in rs.items()}
        return {"pred": bool(T["rule"](a)), "answers": a, "probs": {k: v["p"] for k, v in rs.items()},
                "s": max(v["s"] for v in rs.values()),
                "in": sum(v["in"] for v in rs.values()), "out": sum(v["out"] for v in rs.values()), "calls": len(rs)}
    if method == "opus1":
        r = ask_opus(prompt(T["noun"], item["text"], T["one"]), "You are a classifier. Reply with exactly one word: Yes or No.")
        return {"pred": r["text"].lower().startswith("yes"), "raw": r["text"][:20], "s": r["s"], "in": r["in"], "out": r["out"], "calls": 1}
    if method == "opus5":
        qs = "\n".join(f"{k}: {q}" for k, q in T["checks"].items())
        content = (f"{T['noun']}:\n{item['text']}\n\nAnswer each question Yes or No.\n{qs}\n\n"
                   f"Reply with only a JSON object mapping each key to true or false.")
        r = ask_opus(content, "You are a classifier. Reply with only the JSON object requested.")
        txt = r["text"]
        a = json.loads(txt[txt.find("{"): txt.rfind("}") + 1])
        a = {k: bool(a.get(k)) for k in T["checks"]}
        return {"pred": bool(T["rule"](a)), "answers": a, "s": r["s"], "in": r["in"], "out": r["out"], "calls": 1}
    raise SystemExit(f"unknown method {method}")


def main():
    task, method = sys.argv[1], sys.argv[2]
    items = json.load(open(TASKS[task]["data"]))
    if len(sys.argv) > 3:
        items = items[: int(sys.argv[3])]
    os.makedirs("results", exist_ok=True)
    path = f"results/{task}-{method}{os.environ.get('SUFFIX', '')}.jsonl"
    done = {json.loads(l)["i"] for l in open(path)} if os.path.exists(path) else set()
    conc = int(os.environ.get("CONC", "6" if method.startswith("opus") else "16"))
    todo = [i for i in range(len(items)) if i not in done]
    t0 = time.time()
    with open(path, "a") as f, ThreadPoolExecutor(conc) as ex:
        for i, r in zip(todo, ex.map(lambda i: run_item(task, method, items[i]), todo)):
            r.update({"i": i, "label": items[i]["label"]})
            f.write(json.dumps(r) + "\n")
            f.flush()
    print(f"{task} {method}: {len(todo)} items in {time.time() - t0:.0f}s at concurrency {conc}")


if __name__ == "__main__":
    main()
