#!/usr/bin/env python3
# Last updated: 2026-07-03
#
# gpt_brad.py — minimal bridge to the OpenAI Responses API (/v1/responses).
# Reads the key from $OPENAI_API_KEY. No third-party packages required.
#
# Subcommands:
#   model          Print the model id that will be used (override or auto-detected).
#   ask            Read a JSON request on stdin, print the assistant's reply text.
#                  stdin JSON: {"system": "...", "messages": [{"role","content"}, ...],
#                              "model": "optional-override"}
#
# Model selection order:
#   1. $GPT_BRAD_MODEL if set
#   2. newest flagship gpt-* returned by the /models endpoint
#   3. FALLBACK_MODEL below

import json
import os
import re
import sys
import urllib.error
import urllib.request

API_BASE = "https://api.openai.com/v1"
FALLBACK_MODEL = "gpt-5"
TIMEOUT = 180
SECRETS = os.path.expanduser("~/.config/secrets/api-keys.env")

# Substrings that mark a model we never want to pick automatically.
_EXCLUDE = (
    "audio", "realtime", "search", "image", "tts", "transcribe",
    "moderation", "embedding", "instruct", "vision-preview", "codex",
)


def _key():
    k = os.environ.get("OPENAI_API_KEY", "").strip()
    if k:
        return k
    # Fall back to the on-disk secrets file (same source ~/.zshenv exports from),
    # so the bridge works even in a shell where the env var wasn't inherited.
    try:
        with open(SECRETS) as f:
            for line in f:
                m = re.search(r'OPENAI_API_KEY\s*=\s*["\']?([^"\'\n]+)', line)
                if m:
                    return m.group(1).strip()
    except OSError:
        pass
    sys.exit(f"OPENAI_API_KEY not in env and not found in {SECRETS}.")


def _request(method, path, payload=None):
    url = API_BASE + path
    data = json.dumps(payload).encode() if payload is not None else None
    req = urllib.request.Request(url, data=data, method=method)
    req.add_header("Authorization", "Bearer " + _key())
    req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        body = e.read().decode(errors="replace")
        sys.exit(f"OpenAI API error {e.code}: {body}")
    except urllib.error.URLError as e:
        sys.exit(f"Could not reach OpenAI: {e.reason}")


def _rank(model_id):
    """Higher is better. Newest flagship gpt-* wins; mini/nano demoted."""
    nums = re.findall(r"\d+(?:\.\d+)?", model_id)
    version = max((float(n) for n in nums), default=0.0)
    size = 0
    if "nano" in model_id:
        size = -2
    elif "mini" in model_id:
        size = -1
    # A bare "-latest" alias is desirable when present.
    alias = 0.5 if model_id.endswith("latest") else 0.0
    return (version, size, alias)


def detect_model():
    override = os.environ.get("GPT_BRAD_MODEL", "").strip()
    if override:
        return override
    data = _request("GET", "/models").get("data", [])
    candidates = [
        m["id"] for m in data
        if m.get("id", "").startswith("gpt-")
        and not any(x in m["id"] for x in _EXCLUDE)
    ]
    if not candidates:
        return FALLBACK_MODEL
    return max(candidates, key=_rank)


def _extract_text(out):
    """Pull the assistant text out of a /v1/responses payload."""
    chunks = []
    for item in out.get("output", []):
        if item.get("type") == "message":
            for c in item.get("content", []):
                if c.get("type") == "output_text":
                    chunks.append(c.get("text", ""))
    return "".join(chunks).strip()


def ask():
    try:
        req = json.load(sys.stdin)
    except json.JSONDecodeError as e:
        sys.exit(f"Bad JSON on stdin: {e}")

    model = (req.get("model") or "").strip() or detect_model()
    messages = list(req.get("messages") or [])
    if not messages:
        sys.exit("No messages provided.")

    # Responses API: system prompt goes in `instructions`, the turns in `input`.
    payload = {"model": model, "input": messages}
    system = req.get("system")
    if system:
        payload["instructions"] = system

    out = _request("POST", "/responses", payload)
    text = _extract_text(out)
    if not text:
        sys.exit("No text in response:\n" + json.dumps(out, indent=2))
    print(text)


def main():
    cmd = sys.argv[1] if len(sys.argv) > 1 else ""
    if cmd == "model":
        print(detect_model())
    elif cmd == "ask":
        ask()
    else:
        sys.exit("Usage: gpt_brad.py {model|ask}")


if __name__ == "__main__":
    main()
