"""Call any OpenAI-compatible chat completions endpoint with the standard library.

Works with hosted providers that expose this API shape and with local servers
(Ollama, llama.cpp server, vLLM, LM Studio). Configure with environment variables:

    LLM_BASE_URL   e.g. https://api.openai.com/v1  or  http://localhost:11434/v1
    LLM_API_KEY    API key (local servers often accept any value)
    LLM_MODEL      model name as the server knows it
"""

from __future__ import annotations

import json
import os
import urllib.request


def make_llm(base_url: str = None, api_key: str = None, model: str = None,
             temperature: float = 0.0, timeout: float = 120):
    base_url = (base_url or os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1")).rstrip("/")
    api_key = api_key or os.environ.get("LLM_API_KEY", "not-needed")
    model = model or os.environ.get("LLM_MODEL")
    if not model:
        raise ValueError("set LLM_MODEL (or pass model=)")

    def call(system: str, user: str) -> str:
        payload = {
            "model": model,
            "temperature": temperature,
            "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
        }
        req = urllib.request.Request(
            base_url + "/chat/completions",
            data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"},
            method="POST",
        )
        with urllib.request.urlopen(req, timeout=timeout) as r:
            data = json.loads(r.read())
        return data["choices"][0]["message"]["content"] or ""

    return call
