#!/usr/bin/env python3
"""Check LingDT-Decision-Fast-1.0 against your own labelled examples.

Runs on a stock macOS Python 3 (standard library only, no pip install).

Usage:
    export OPENROUTER_API_KEY=...            # your OpenRouter key
    python3 lingdt_check.py quota            # show today's free-model quota
    python3 lingdt_check.py one "Text ..."   # single demo decision
    python3 lingdt_check.py eval labels.csv  # accuracy + calibration on a CSV

labels.csv needs two columns: text,label   (label must be one of LABELS below).
Every row is one request. On an account with fewer than 10 purchased credits,
OpenRouter allows 50 requests per UTC day for :free models, so keep the file
small or use --limit.
"""
import csv
import json
import os
import sys
import time
import urllib.error
import urllib.request

BASE = os.environ.get("OPENROUTER_BASE", "https://openrouter.ai")
MODEL = os.environ.get("LINGDT_MODEL", "antdigital/lingdt-decision-fast-1.0:free")

# Adapt these to your own task. Keys must be short ASCII names.
INSTRUCTIONS = "Which team should handle this support message?"
LABELS = {
    "billing": "Charges, invoices, refunds and payment problems.",
    "technical": "Bugs, crashes, errors and setup problems.",
    "account": "Login, password, profile and access questions.",
    "other": "Anything that fits none of the other teams.",
}


def _key():
    key = os.environ.get("OPENROUTER_API_KEY")
    if not key:
        sys.exit("OPENROUTER_API_KEY is not set.")
    return key


def _request(method, path, payload=None, retries=3):
    data = json.dumps(payload).encode() if payload is not None else None
    for attempt in range(retries + 1):
        req = urllib.request.Request(
            BASE + path, data=data, method=method,
            headers={"Authorization": f"Bearer {_key()}", "Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                return json.loads(r.read().decode())
        except urllib.error.HTTPError as e:
            body = e.read().decode(errors="replace")
            if e.code == 429 and attempt < retries:
                wait = float(e.headers.get("Retry-After") or 2 ** (attempt + 2))
                print(f"429 rate limit, waiting {wait:.0f}s ...", file=sys.stderr)
                time.sleep(wait)
                continue
            raise SystemExit(f"HTTP {e.code}: {body[:500]}")


def quota():
    info = _request("GET", "/api/v1/key").get("data", {})
    print(json.dumps(info.get("free_model_daily_requests", info), indent=2))


def decide(text):
    payload = {
        "model": MODEL,
        "state": text,
        "questions": {
            "team": {"type": "choice", "instructions": INSTRUCTIONS, "criteria": LABELS},
            "needs_human": {"type": "noul",
                            "instructions": "Does this message need a human agent right away?"},
        },
    }
    return _request("POST", "/api/alpha/decisions", payload)


def read_choice(resp, key="team"):
    """Return (choice, confidence) or (None, None). A refusal, a missing key or an
    unexpected type counts as NOT answered, never as a safe default."""
    ans = (resp.get("answers") or {}).get(key)
    if not ans or ans.get("type") != "choice":
        return None, None
    return ans.get("choice"), ans.get("confidence")


def one(text):
    resp = decide(text)
    print(json.dumps(resp.get("answers"), indent=2))
    print("usage:", json.dumps(resp.get("usage")))


def evaluate(path, limit=None):
    rows = list(csv.DictReader(open(path, newline="", encoding="utf-8")))[:limit]
    bad = [r["label"] for r in rows if r["label"] not in LABELS]
    if bad:
        sys.exit(f"Unknown labels in CSV: {sorted(set(bad))}")
    results = []  # (correct, confidence)
    unanswered = 0
    for i, r in enumerate(rows, 1):
        choice, conf = read_choice(decide(r["text"]))
        if choice is None:
            unanswered += 1
            continue
        results.append((choice == r["label"], conf or 0.0))
        print(f"{i}/{len(rows)} label={r['label']:<10} model={choice:<10} conf={conf:.3f}")
    n = len(results)
    if n == 0:
        sys.exit("No answered rows.")
    acc = sum(c for c, _ in results) / n
    print(f"\nanswered: {n}/{len(rows)}  unanswered (refusal/missing): {unanswered}")
    print(f"accuracy on answered rows: {acc:.1%}")
    # Calibration: does 0.9 confidence mean ~90% correct on YOUR data?
    print("\nconfidence bin   rows  accuracy")
    for lo, hi in [(0.0, 0.5), (0.5, 0.7), (0.7, 0.9), (0.9, 1.01)]:
        b = [c for c, p in results if lo <= p < hi]
        if b:
            print(f"{lo:.1f}–{min(hi, 1.0):.1f}        {len(b):>4}  {sum(b) / len(b):.1%}")


if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] not in {"quota", "one", "eval"}:
        sys.exit(__doc__)
    cmd = sys.argv[1]
    if cmd == "quota":
        quota()
    elif cmd == "one":
        one(" ".join(sys.argv[2:]) or "I was charged twice for my subscription this month.")
    else:
        lim = None
        if "--limit" in sys.argv:
            lim = int(sys.argv[sys.argv.index("--limit") + 1])
        evaluate(sys.argv[2], lim)
