"""Live Jev calls through OpenRouter's decisions endpoint (and GPT-6 Luna through chat completions),
with a global cost cap and resume.

usage: python -I jev_live.py KEYFILE DATA_DIR OUT_DIR {check|smoke|run|luna}
         [--set bench500|rest|full] [--variant names|examplesK] [--model typesafe/jev-1.13]
         [--llm openai/gpt-6-luna] [--limit N] [--cap 0.60] [--workers 8] [--pace 0]
         [--example-seed 0] [--shuffle-options SEED]
`run` calls Jev, `luna` calls the LLM; examplesK puts K training messages per intent in the options.
The key is read from KEYFILE and never printed.
"""

import argparse
import csv
import json
import random
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

import requests

ap = argparse.ArgumentParser()
ap.add_argument("keyfile")
ap.add_argument("data")
ap.add_argument("out")
ap.add_argument("mode", choices=["check", "smoke", "run", "luna"])
ap.add_argument("--set", default="bench500", choices=["bench500", "rest", "full"])
ap.add_argument(
    "--variant", default="names", help="names, or examplesK for K training messages per intent"
)
ap.add_argument(
    "--cap",
    type=float,
    default=0.60,
    help="stop when total spend across all runs passes this (USD)",
)
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--model", default="typesafe/jev-1.13")
ap.add_argument("--llm", default="openai/gpt-6-luna")
ap.add_argument("--limit", type=int, default=None, help="only the first N messages of the set")
ap.add_argument(
    "--pace", type=float, default=0.0, help="seconds to wait before each call (rate limits)"
)
ap.add_argument(
    "--example-seed", type=int, default=0, help="seed for drawing the K labeled messages per intent"
)
ap.add_argument(
    "--shuffle-options",
    type=int,
    default=None,
    help="shuffle the order of the options with this seed (default: alphabetical)",
)
a = ap.parse_args()

raw = Path(a.keyfile).read_text(encoding="utf8").strip()
key = next(
    (t for t in raw.replace("=", " ").split() if t.startswith("sk-or-")),
    raw.splitlines()[0].strip(),
)
H = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
S = requests.Session()
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
LEDGER = out / "spend.jsonl"  # every paid call across every run, for the global cap

if a.mode == "check":
    r = S.get("https://openrouter.ai/api/v1/key", headers=H, timeout=30)
    d = r.json().get("data", {})
    print(
        "status",
        r.status_code,
        {k: d.get(k) for k in ("label", "usage", "limit", "limit_remaining", "is_free_tier")},
    )
    r = S.get("https://openrouter.ai/api/v1/credits", headers=H, timeout=30)
    print("credits", r.status_code, r.json().get("data"))
    sys.exit()

data = Path(a.data)
with open(data / "test.csv", encoding="utf8") as f:
    rows = list(csv.DictReader(f))
with open(data / "train.csv", encoding="utf8") as f:
    train = list(csv.DictReader(f))
texts, gold = [r["text"] for r in rows], [r["category"] for r in rows]
labels = sorted(set(gold))

# Fixed sample: shuffle all test indices with seed 42 and keep the first 500.
idx = list(range(len(texts)))
random.Random(42).shuffle(idx)
sets = {"bench500": idx[:500], "rest": idx[500:], "full": idx}
todo = [1] if a.mode == "smoke" else sets[a.set][: a.limit]

if a.variant == "names":
    criteria = {l: l.replace("_", " ") for l in labels}
else:  # K training messages per intent appended to the description
    k = int(a.variant.removeprefix("examples"))
    rng = random.Random(a.example_seed)
    by = {}
    for r in train:
        by.setdefault(r["category"], []).append(r["text"])
    criteria = {
        l: l.replace("_", " ") + ". Examples: " + " | ".join(rng.sample(by[l], k)) for l in labels
    }
if a.shuffle_options is not None:  # same options, different order
    order = labels[:]
    random.Random(a.shuffle_options).shuffle(order)
    criteria = {l: criteria[l] for l in order}
Q = {
    "intent": {
        "type": "choice",
        "instructions": "Which banking customer-support intent does this message express?",
        "criteria": criteria,
    }
}
LUNA_SYS = (
    "Classify a bank customer's message into exactly one intent from the allowed list. "
    'Answer with JSON only: {"label": "<intent>", "confidence": <probability from 0 to 1 that the label is right>}.'
)

# Same options and, for examplesK, the same example messages Jev gets; the shared prefix lets the provider cache it.
LUNA_OPTIONS = (
    "Allowed intents: " + ", ".join(criteria)
    if a.variant == "names"
    else "Allowed intents, each with example messages:\n"
    + "\n".join(f"- {l}: {d}" for l, d in criteria.items())
)
tag = {
    "run": f"{a.variant}_{a.set}",
    "luna": "luna_" + ("" if a.variant == "names" else a.variant + "_") + a.set,
}.get(a.mode, "smoke")
if a.example_seed and a.variant != "names":
    tag += f"_seed{a.example_seed}"
if a.shuffle_options is not None:
    tag += f"_shuffle{a.shuffle_options}"
if a.mode == "run" and a.model != "typesafe/jev-1.13":
    tag = a.model.split("/")[-1] + "_" + tag
pred_file = out / f"jev_{tag}.jsonl"
done = {}
if pred_file.exists():
    for l in pred_file.read_text(encoding="utf8").splitlines():
        if l.strip():
            r = json.loads(l)
            done[r["i"]] = r
lock = threading.Lock()
spent = (
    sum(json.loads(l)["cost"] for l in LEDGER.read_text(encoding="utf8").splitlines() if l.strip())
    if LEDGER.exists()
    else 0.0
)
print(
    f"already spent {spent:.4f} USD across runs; cap {a.cap}; todo {len(todo) - len(done)}",
    flush=True,
)
stop = threading.Event()


def call_luna(i):
    body = {
        "model": a.llm,
        "temperature": 0,
        "reasoning": {"effort": "minimal"},
        "response_format": {"type": "json_object"},
        "usage": {"include": True},
        "messages": [
            {"role": "system", "content": LUNA_SYS},
            {"role": "user", "content": LUNA_OPTIONS + "\n\nMessage:\n" + texts[i]},
        ],
    }
    for attempt in range(6):
        time.sleep(a.pace)
        t0 = time.perf_counter()
        r = S.post(
            "https://openrouter.ai/api/v1/chat/completions", headers=H, json=body, timeout=120
        )
        lat = (time.perf_counter() - t0) * 1000
        if r.status_code in (429, 500, 502, 503) and attempt < 5:
            time.sleep(15 if r.status_code == 429 else 2**attempt)
            continue
        if r.status_code != 200:
            return {"i": i, "error": f"{r.status_code} {r.text[:300]}"}
        d = r.json()
        u = d.get("usage") or {}
        try:
            c = d["choices"][0]["message"]["content"]
            o = json.loads(c[c.find("{") : c.rfind("}") + 1])
            pred, conf = o.get("label"), min(max(float(o.get("confidence", 0.5)), 0.0), 1.0)
        except Exception:
            pred, conf = None, 0.0
        if pred not in labels:
            pred = "__invalid__"
        return {
            "i": i,
            "gold": gold[i],
            "pred": pred,
            "conf": conf,
            "latency_ms": lat,
            "cost": u.get("cost"),
            "usage": u,
            "model": d.get("model"),
        }


def call(i):
    if stop.is_set():
        return None
    if a.mode == "luna":
        return call_luna(i)
    body = {"model": a.model, "state": texts[i], "questions": Q}
    for attempt in range(4):
        t0 = time.perf_counter()
        r = S.post("https://openrouter.ai/api/alpha/decisions", headers=H, json=body, timeout=60)
        lat = (time.perf_counter() - t0) * 1000
        if r.status_code in (429, 500, 502, 503) and attempt < 3:
            time.sleep(2**attempt)
            continue
        if r.status_code != 200:
            return {"i": i, "error": f"{r.status_code} {r.text[:300]}"}
        d = r.json()
        ans = d["answers"]["intent"]
        probs = ans.get("probabilities") or {ans["choice"]: ans.get("confidence", 1.0)}
        probs = {k: float(v) for k, v in probs.items()}
        u = d.get("usage") or {}
        pred = max(probs, key=probs.get)
        return {
            "i": i,
            "gold": gold[i],
            "pred": pred,
            "conf": probs[pred],
            "latency_ms": lat,
            "cost": u.get("cost", u.get("total_cost")),
            "usage": u,
            "model": d.get("model"),
            **({"raw": d} if a.mode == "smoke" else {}),
        }


errors = 0
with (
    ThreadPoolExecutor(a.workers) as ex,
    open(pred_file, "a", encoding="utf8") as pf,
    open(LEDGER, "a", encoding="utf8") as lf,
):
    futs = [ex.submit(call, i) for i in todo if i not in done]
    for n, fu in enumerate(as_completed(futs), 1):
        r = fu.result()
        if r is None:
            continue
        if "error" in r:
            errors += 1
            print("error", r["error"], flush=True)
            if errors >= 10:
                stop.set()
            continue
        with lock:
            c = float(r["cost"] or 0)
            spent += c
            lf.write(json.dumps({"tag": tag, "i": r["i"], "cost": c}) + "\n")
            lf.flush()
            pf.write(json.dumps(r) + "\n")
            pf.flush()
            done[r["i"]] = r
            if spent > a.cap and not stop.is_set():
                print(f"cost cap reached at {spent:.4f} USD, stopping", flush=True)
                stop.set()
        if n % 100 == 0:
            print(f"{n}/{len(futs)} spent {spent:.4f}", flush=True)

rs = [done[i] for i in todo if i in done]
if a.mode == "smoke":
    print(json.dumps(rs[0], indent=1)[:3000]) if rs else print("no result")
acc = sum(r["pred"] == r["gold"] for r in rs) / max(len(rs), 1)
cs = [float(r["cost"] or 0) for r in rs]
lats = sorted(r["latency_ms"] for r in rs) or [0]
print(
    json.dumps(
        {
            "tag": tag,
            "n": len(rs),
            "of": len(todo),
            "errors": errors,
            "accuracy": round(acc, 4),
            "cost_this_set": round(sum(cs), 5),
            "cost_per_call": (sum(cs) / len(cs)) if cs else None,
            "p50_ms": round(lats[len(lats) // 2]),
            "total_spent_all_runs": round(spent, 5),
        }
    )
)
