"""Ollama local provider."""

from __future__ import annotations

from typing import Any

import httpx

from ..utils.logger import Logger
from .base_provider import BaseProvider


class OllamaProvider(BaseProvider):
    """Provider using local Ollama instance."""

    name = "Ollama (Local)"
    type = "api"

    def __init__(self, base_url: str = "http://localhost:11434", model: str = "llama2") -> None:
        self.base_url = base_url.rstrip("/")
        self.model = model
        self.client = httpx.Client(base_url=self.base_url, timeout=120.0)

    def test_connection(self) -> bool:
        """Test connection to Ollama."""
        try:
            response = self.client.get("/api/tags")
            return response.status_code == 200
        except Exception as e:
            Logger.error("Ollama connection test failed", e)
            return False

    def execute(self, skill_content: str, user_input: str, context: dict[str, Any]) -> str:
        """Execute task using Ollama."""
        system_prompt = self._build_system_prompt(skill_content, context)

        Logger.info("Executing with Ollama", {"model": self.model, "input": user_input[:100]})

        try:
            response = self.client.post(
                "/api/generate",
                json={
                    "model": self.model,
                    "prompt": f"{system_prompt}\n\nUser: {user_input}",
                    "stream": False,
                    "options": {"temperature": 0.7},
                },
            )

            response.raise_for_status()
            data = response.json()
            return data.get("response", "")

        except Exception as e:
            Logger.error("Ollama execution failed", e)
            raise RuntimeError(f"Ollama error: {e}")

    def _build_system_prompt(self, skill_content: str, context: dict[str, Any]) -> str:
        """Build system prompt."""
        prompt = (
            "You are a marketing assistant for Reply Cash, "
            "a stablecoin-to-mobile-money payment platform."
        )

        if skill_content:
            prompt += f"\n\n{skill_content}"

        skill = context.get("skill")
        if skill:
            prompt += f"\n\nCurrent task: Use the {skill} skill to help the user."

        prompt += """

Guidelines:
- Be concise and actionable
- Focus on Reply Cash's value proposition
- Always suggest next steps
- If creating content, mention you'll submit it for approval"""

        return prompt

    def get_model(self) -> str:
        """Get model name."""
        return self.model

    def list_models(self) -> list[str]:
        """List available models."""
        try:
            response = self.client.get("/api/tags")
            response.raise_for_status()
            data = response.json()
            return [m["name"] for m in data.get("models", [])]
        except Exception:
            return []
