"""LLM backends used by the GAIA agent.

The agent only needs one primitive: ``chat(messages, max_tokens) -> str``.
Three backends are provided so the same agent code works locally and on a
Hugging Face Space:

* ``mlx``         - local model through ``mlx-lm`` (default on Apple Silicon, no API key)
* ``openai``      - any OpenAI compatible endpoint (HF router, Groq, Gemini, vLLM, ...)
* ``pollinations``- keyless public endpoint, used as a last resort (rate limited)

Selection order is controlled by the ``GAIA_LLM`` environment variable.
"""

from __future__ import annotations

import os
import threading
import time

DEFAULT_MLX_MODEL = os.getenv("GAIA_MLX_MODEL", "mlx-community/Qwen3-8B-4bit")
POLLINATIONS_URL = "https://text.pollinations.ai/openai"
HF_ROUTER_URL = "https://router.huggingface.co/v1"


class LLMError(RuntimeError):
    """Raised when a backend cannot produce a completion."""


class BaseLLM:
    name = "base"

    def chat(self, messages: list[dict], max_tokens: int = 700, temperature: float = 0.0) -> str:
        raise NotImplementedError

    def reset(self) -> None:
        """Drop any internal state kept between calls (safe to ignore)."""


class MLXLLM(BaseLLM):
    """Local inference with ``mlx-lm``; keeps a KV cache for the shared prefix."""

    name = "mlx"
    # MLX generation is not thread safe, so all calls share one lock.
    _lock = threading.Lock()

    def __init__(self, model_id: str | None = None):
        try:
            from mlx_lm import load
            from mlx_lm.models.cache import make_prompt_cache
        except ImportError as exc:  # pragma: no cover - depends on platform
            raise LLMError("mlx-lm is not installed") from exc

        self.model_id = model_id or DEFAULT_MLX_MODEL
        self.model, self.tokenizer = load(self.model_id)
        self._make_cache = make_prompt_cache
        self._cache = None
        self._cached_ids: list[int] = []
        self._cache_enabled = True

    def reset(self) -> None:
        self._cache = None
        self._cached_ids = []

    def _render(self, messages: list[dict]) -> str:
        template = self.tokenizer.apply_chat_template
        kwargs = {"tokenize": False, "add_generation_prompt": True}
        try:
            # Qwen3 style templates accept this flag; others do not.
            return template(messages, enable_thinking=False, **kwargs)
        except TypeError:
            return template(messages, **kwargs)

    def _prepare(self, ids: list[int]):
        """Return (prompt ids to feed, cache) reusing the longest shared prefix."""
        from mlx_lm.models.cache import trim_prompt_cache

        if not self._cache_enabled:
            return ids, None
        try:
            if self._cache is None:
                self._cache = self._make_cache(self.model)
                self._cached_ids = []
            common = 0
            limit = min(len(ids), len(self._cached_ids))
            while common < limit and ids[common] == self._cached_ids[common]:
                common += 1
            drop = len(self._cached_ids) - common
            if drop > 0:
                trim_prompt_cache(self._cache, drop)
                self._cached_ids = self._cached_ids[:common]
            return ids[common:], self._cache
        except Exception:
            # Any cache bookkeeping problem simply falls back to a cold prompt.
            self._cache_enabled = False
            self.reset()
            return ids, None

    def chat(self, messages: list[dict], max_tokens: int = 700, temperature: float = 0.0) -> str:
        from mlx_lm import stream_generate
        from mlx_lm.sample_utils import make_sampler

        prompt = self._render(messages)
        ids = self.tokenizer.encode(prompt)
        with self._lock:
            feed, cache = self._prepare(ids)
            kwargs = {"max_tokens": max_tokens, "sampler": make_sampler(temp=temperature)}
            if cache is not None:
                kwargs["prompt_cache"] = cache
            pieces: list[str] = []
            produced: list[int] = []
            for response in stream_generate(self.model, self.tokenizer, feed, **kwargs):
                pieces.append(response.text)
                token = getattr(response, "token", None)
                if token is not None:
                    produced.append(int(token))
            if cache is not None:
                self._cached_ids = ids + produced
            text = "".join(pieces)
        return text.strip()


class OpenAICompatLLM(BaseLLM):
    """Any endpoint that speaks the OpenAI chat-completions dialect."""

    name = "openai"

    def __init__(self, base_url: str | None = None, api_key: str | None = None, model: str | None = None):
        try:
            from openai import OpenAI
        except ImportError as exc:  # pragma: no cover
            raise LLMError("openai package is not installed") from exc

        self.model = model or os.getenv("GAIA_MODEL") or os.getenv("OPENAI_MODEL") or "gpt-4o-mini"
        self.client = OpenAI(
            base_url=base_url or os.getenv("OPENAI_BASE_URL") or None,
            api_key=api_key or os.getenv("OPENAI_API_KEY") or "not-needed",
            timeout=120.0,
            max_retries=2,
        )

    def chat(self, messages: list[dict], max_tokens: int = 700, temperature: float = 0.0) -> str:
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=messages,
                max_tokens=max_tokens,
                temperature=temperature,
            )
        except Exception as exc:
            raise LLMError(f"{self.name} call failed: {exc}") from exc
        return (response.choices[0].message.content or "").strip()


class PollinationsLLM(OpenAICompatLLM):
    """Keyless fallback. Throttled to roughly one reply every 45 s per IP."""

    name = "pollinations"
    _lock = threading.Lock()
    _min_interval = 45.0
    _last_call = 0.0

    def __init__(self, model: str | None = None):
        super().__init__(
            base_url=POLLINATIONS_URL,
            api_key=os.getenv("POLLINATIONS_TOKEN") or "none",
            model=model or "openai",
        )

    def chat(self, messages: list[dict], max_tokens: int = 700, temperature: float = 0.0) -> str:
        with self._lock:
            wait = self._min_interval - (time.monotonic() - self._last_call)
            if wait > 0:
                time.sleep(wait)
            try:
                return super().chat(messages, max_tokens=max_tokens, temperature=temperature)
            finally:
                self._last_call = time.monotonic()


def build_llm(preference: str | None = None) -> BaseLLM:
    """Create the first backend that is actually available."""
    preference = (preference or os.getenv("GAIA_LLM") or "auto").lower()
    if preference != "auto":
        return _instantiate(preference)

    errors: list[str] = []
    for candidate in _auto_order():
        try:
            llm = _instantiate(candidate)
            print(f"[llm] using backend '{candidate}'")
            return llm
        except Exception as exc:
            errors.append(f"{candidate}: {exc}")
    raise LLMError("no LLM backend available -> " + "; ".join(errors))


def _auto_order() -> list[str]:
    order: list[str] = []
    if os.getenv("OPENAI_API_KEY") or os.getenv("OPENAI_BASE_URL"):
        order.append("openai")
    if os.getenv("HF_TOKEN"):
        order.append("hf")
    order.append("mlx")
    order.append("pollinations")
    return order


def _instantiate(name: str) -> BaseLLM:
    if name == "mlx":
        return MLXLLM()
    if name == "openai":
        return OpenAICompatLLM()
    if name == "hf":
        token = os.getenv("HF_TOKEN")
        if not token:
            raise LLMError("HF_TOKEN is not set")
        return OpenAICompatLLM(
            base_url=HF_ROUTER_URL,
            api_key=token,
            model=os.getenv("GAIA_MODEL", "Qwen/Qwen3-32B"),
        )
    if name == "pollinations":
        return PollinationsLLM()
    raise LLMError(f"unknown backend '{name}'")
