#!/usr/bin/env python3
"""Rulebench gate: check a changed model against the current one before it ships.

Your models run where they are (your laptop, a Kaggle notebook, a GPU box, CI). This script asks them the gate's
messages, sends only their replies to Rulebench for grading, and prints the verdict. The weights never leave your
machine.

Command line, with two OpenAI-compatible endpoints (vLLM, Ollama, LM Studio, llama.cpp server, TGI):

    export WEIGHTSHIP_API_KEY=ws_...
    python gate.py --audit AUDIT_ID \
        --base-url http://localhost:8000/v1 --base-model qwen-base \
        --candidate-url http://localhost:8001/v1 --candidate-model qwen-edited

    # or make the audit from your bot's instructions:
    python gate.py --prompt-file prompts/support.md --base-url ... --candidate-url ...

From Python, with any function that takes chat messages and returns the reply text:

    from gate import run_gate
    result = run_gate(audit_id="...", base=lambda msgs: chat(base_model, msgs), candidate=lambda msgs: chat(edited, msgs))

Exit code: 0 passed, 1 failed (the changed model is worse), 2 something went wrong.
Docs: https://weightship.com/rulebench/gate
"""
from __future__ import annotations

import argparse
import concurrent.futures as cf
import json
import os
import sys
import time
import urllib.error
import urllib.request
from typing import Callable

API = os.environ.get("WEIGHTSHIP_API", "https://api.weightship.com").rstrip("/")
Chat = Callable[[list], str]


class GateError(Exception):
    pass


def _request(method: str, path: str, body: dict | None = None, key: str | None = None, timeout: int = 120) -> dict:
    key = key or os.environ.get("WEIGHTSHIP_API_KEY", "")
    if not key:
        raise GateError("Set WEIGHTSHIP_API_KEY (create one at https://weightship.com/dashboard/keys).")
    req = urllib.request.Request(
        API + path,
        data=json.dumps(body).encode() if body is not None else None,
        method=method,
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json", "User-Agent": "rulebench-gate/1"},
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.loads(r.read())
    except urllib.error.HTTPError as e:
        try:
            msg = json.loads(e.read())["error"]["message"]
        except Exception:
            msg = f"HTTP {e.code}"
        raise GateError(msg) from None


def openai_chat(base_url: str, model: str, api_key: str | None = None, max_tokens: int = 1024, temperature: float = 0.0) -> Chat:
    """A chat function for any OpenAI-compatible endpoint. Greedy decoding by default, so reruns compare cleanly."""
    url = base_url.rstrip("/") + "/chat/completions"

    def chat(messages: list) -> str:
        body = {"model": model, "messages": messages, "max_tokens": max_tokens, "temperature": temperature}
        headers = {"Content-Type": "application/json"}
        if api_key:
            headers["Authorization"] = f"Bearer {api_key}"
        req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers, method="POST")
        with urllib.request.urlopen(req, timeout=600) as r:
            out = json.loads(r.read())
        return out["choices"][0]["message"].get("content") or ""

    return chat


def _answer(chat: Chat, messages: list, workers: int, name: str) -> dict:
    replies: dict = {}

    def one(m: dict):
        convo = ([{"role": "system", "content": m["system"]}] if m.get("system") else []) + [{"role": "user", "content": m["message"]}]
        try:
            return m["id"], chat(convo)
        except Exception as e:  # a crashed reply counts as a wrong one, not a crashed gate
            return m["id"], f"[no reply: {e}]"

    with cf.ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
        for i, (mid, text) in enumerate(pool.map(one, messages), 1):
            replies[mid] = text
            print(f"\r  {name}: {i}/{len(messages)} replies", end="", file=sys.stderr, flush=True)
    print(file=sys.stderr)
    return replies


def run_gate(
    base: Chat,
    candidate: Chat,
    audit_id: str | None = None,
    prompt: str | None = None,
    skills: bool = True,
    base_label: str = "Current model",
    candidate_label: str = "Changed model",
    max_drop: float | None = None,
    max_rule_drop: float | None = None,
    workers: int = 4,
    api_key: str | None = None,
    quiet: bool = False,
) -> dict:
    """Run both models on the gate's messages, send the replies, wait for the verdict and return it (the API's JSON)."""
    if not audit_id and not prompt:
        raise GateError("Pass audit_id, or prompt (the bot's instructions) to make a new audit.")
    log = (lambda *a: None) if quiet else (lambda *a: print(*a, file=sys.stderr))
    log("Fetching the gate's messages…")
    got = _request("POST", "/v1/rulebench/gates/messages", {"audit_id": audit_id, "skills": skills} if audit_id else {"prompt": prompt, "skills": skills}, api_key)
    messages = got["messages"]
    log(f"{len(messages)} messages (audit {got['audit_id']}).")
    b = _answer(base, messages, workers, base_label)
    c = _answer(candidate, messages, workers, candidate_label)
    body = {
        "audit_id": got["audit_id"],
        "base": {"label": base_label, "replies": b},
        "candidate": {"label": candidate_label, "replies": c},
        "skills": skills,
        "source": "script",
        "wait": 50,
    }
    if max_drop is not None:
        body["max_drop"] = max_drop
    if max_rule_drop is not None:
        body["max_rule_drop"] = max_rule_drop
    log("Grading…")
    gate = _request("POST", "/v1/rulebench/gates", body, api_key)
    deadline = time.time() + 900
    while gate["status"] != "done" and time.time() < deadline:
        gate = _request("GET", f"/v1/rulebench/gates/{gate['id']}?wait=50", None, api_key)
    return gate


def print_result(g: dict) -> int:
    pct = lambda x: "–" if x is None else f"{round(x * 100)}%"
    verdict = {"pass": "PASSED", "fail": "FAILED", "error": "ERROR", "pending": "STILL RUNNING"}[g["verdict"]]
    print(f"\n{verdict}: {g['name']}")
    for r in g["reasons"]:
        print(f"  - {r}")
    if g.get("rules"):
        print(f"\n  Rules kept: {pct(g['rules']['before'])} -> {pct(g['rules']['after'])} on {g['rules']['messages']} messages")
    if g.get("skills"):
        print(f"  Everyday skills: {pct(g['skills']['before'])} -> {pct(g['skills']['after'])}")
        for s in g["skills"]["by_skill"]:
            mark = "  <- worse" if s["failed"] else ""
            print(f"    {s['label']:<28} {pct(s['before']):>5} -> {pct(s['after']):<5}{mark}")
    print(f"\n  Report: {g['url']}")
    return {"pass": 0, "fail": 1}.get(g["verdict"], 2)


def main() -> int:
    p = argparse.ArgumentParser(description="Check a changed model against the current one with Rulebench.")
    src = p.add_mutually_exclusive_group(required=True)
    src.add_argument("--audit", help="audit id whose messages to use")
    src.add_argument("--prompt-file", help="the bot's system prompt, to make a new audit")
    for side in ("base", "candidate"):
        p.add_argument(f"--{side}-url", required=True, help=f"OpenAI-compatible base URL of the {side} model, e.g. http://localhost:8000/v1")
        p.add_argument(f"--{side}-model", required=True, help=f"model name the {side} endpoint serves")
        p.add_argument(f"--{side}-key-env", help=f"environment variable holding the {side} endpoint's API key, if it needs one")
        p.add_argument(f"--{side}-label", help=f"name to show for the {side} model")
    p.add_argument("--no-skills", action="store_true", help="skip the everyday-skills prompts")
    p.add_argument("--max-drop", type=float, help="largest allowed drop in replies keeping every rule (default 0.05)")
    p.add_argument("--max-rule-drop", type=float, help="largest allowed drop for one rule or skill (default 0.10)")
    p.add_argument("--max-tokens", type=int, default=1024)
    p.add_argument("--workers", type=int, default=4, help="parallel requests per model")
    a = p.parse_args()
    key = lambda env: os.environ.get(env) if env else None
    try:
        g = run_gate(
            base=openai_chat(a.base_url, a.base_model, key(a.base_key_env), a.max_tokens),
            candidate=openai_chat(a.candidate_url, a.candidate_model, key(a.candidate_key_env), a.max_tokens),
            audit_id=a.audit,
            prompt=open(a.prompt_file, encoding="utf-8").read() if a.prompt_file else None,
            skills=not a.no_skills,
            base_label=a.base_label or a.base_model,
            candidate_label=a.candidate_label or a.candidate_model,
            max_drop=a.max_drop,
            max_rule_drop=a.max_rule_drop,
            workers=a.workers,
        )
    except GateError as e:
        print(f"Rulebench gate: {e}", file=sys.stderr)
        return 2
    return print_result(g)


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