"""Keiro client — call the EB1 inference gateway.

Usage::

    from keiro import complete

    print(complete("What is machine learning?"))

No ember dependency required. Reads credentials from ``~/.keiro/credentials``
(written by ``keiro setup``).
"""

from __future__ import annotations

import os

import requests

from keiro.credentials import load_credentials
from keiro.defaults import DEFAULT_GATEWAY_URL, DEFAULT_MODEL


def complete(
    prompt: str,
    *,
    model: str = DEFAULT_MODEL,
    api_key: str | None = None,
    base_url: str | None = None,
    timeout: float = 120,
) -> str:
    """Send a prompt to the Keiro gateway and return the response text.

    Args:
        prompt: The user message to send.
        model: Model name (default ``"eb1"``).
        api_key: Override API key (default: from credentials file or env).
        base_url: Override gateway URL (default: from credentials file or env).
        timeout: Request timeout in seconds.

    Returns:
        The model's response text.

    Raises:
        ValueError: If no API key is configured.
        requests.HTTPError: On non-2xx gateway responses.
    """
    resolved_key, resolved_url = _resolve_credentials(api_key, base_url)

    resp = requests.post(
        f"{resolved_url}/v1/chat/completions",
        headers={"Authorization": f"Bearer {resolved_key}"},
        json={
            "model": model,
            "messages": [{"role": "user", "content": prompt}],
        },
        timeout=timeout,
    )
    resp.raise_for_status()
    data = resp.json()
    return data["choices"][0]["message"]["content"]


def _resolve_credentials(
    explicit_key: str | None,
    explicit_url: str | None,
) -> tuple[str, str]:
    """Resolve API key and base URL from args > env > credentials file."""
    key = explicit_key or os.environ.get("KEIRO_API_KEY")
    url = explicit_url or os.environ.get("KEIRO_BASE_URL")

    if not key or not url:
        creds = load_credentials()
        key = key or creds.get("api_key")
        url = url or creds.get("base_url")

    if not key:
        raise ValueError(
            "Keiro API key not configured. Run 'keiro setup' or set KEIRO_API_KEY."
        )

    return key, (url or DEFAULT_GATEWAY_URL).rstrip("/")
