"""Thin DeepSeek (OpenAI-compatible) chat client.

Cheap flagship reasoning for the parts of the brain that need real judgment the
tiny local model can't do — auto-supersession, and later the nightly reflection
engine (insights, opportunities, community summaries, goal-nudges).

Key in .env as DEEPSEEK_API_KEY (permanent 75%-off V4 pricing). Models:
  deepseek-v4-flash — cheap, default for high-volume judging
  deepseek-v4-pro   — flagship (~Opus), for the creative reflection passes
"""
from __future__ import annotations

import json
import os
import urllib.request

_URL = os.environ.get("DEEPSEEK_URL", "https://api.deepseek.com").rstrip("/")
FLASH = "deepseek-v4-flash"
PRO = "deepseek-v4-pro"


def available() -> bool:
    return bool(os.environ.get("DEEPSEEK_API_KEY", ""))


def chat(prompt: str, model: str = FLASH, temperature: float = 0.0,
         max_tokens: int = 1024, system: str | None = None,
         timeout: int = 90) -> str:
    """Single-turn completion; returns the assistant text. Raises on failure."""
    key = os.environ.get("DEEPSEEK_API_KEY", "")
    if not key:
        raise RuntimeError("DEEPSEEK_API_KEY not set")
    msgs = []
    if system:
        msgs.append({"role": "system", "content": system})
    msgs.append({"role": "user", "content": prompt})
    body = json.dumps({"model": model, "messages": msgs,
                       "temperature": temperature, "max_tokens": max_tokens,
                       "stream": False}).encode()
    req = urllib.request.Request(
        _URL + "/chat/completions", data=body,
        headers={"Content-Type": "application/json",
                 "Authorization": f"Bearer {key}"})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        o = json.loads(r.read())
    return ((o.get("choices") or [{}])[0].get("message") or {}
            ).get("content", "").strip()
