"""Ollama LLM provider."""

from __future__ import annotations

import httpx

from milco.llm.base import LLMProvider

DEFAULT_BASE_URL = "http://localhost:11434"
DEFAULT_TIMEOUT = 120.0


class OllamaProvider(LLMProvider):
    def __init__(
        self, model: str, base_url: str | None = None, timeout: float = DEFAULT_TIMEOUT
    ):
        self.model = model
        self.base_url = base_url or DEFAULT_BASE_URL
        self.timeout = timeout

    @property
    def name(self) -> str:
        return "ollama"

    def complete(self, prompt: str, system: str | None = None) -> str:
        payload: dict = {
            "model": self.model,
            "prompt": prompt,
            "stream": False,
        }
        if system:
            payload["system"] = system

        resp = httpx.post(
            f"{self.base_url}/api/generate",
            json=payload,
            timeout=self.timeout,
        )
        resp.raise_for_status()
        return resp.json()["response"]

    def ping(self) -> bool:
        try:
            resp = httpx.get(self.base_url, timeout=5.0)
            return resp.status_code == 200
        except Exception:
            return False
