"""Anthropic API provider."""

from __future__ import annotations

from typing import Any

from anthropic import Anthropic

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


class AnthropicProvider(BaseProvider):
    """Provider using Anthropic Claude API."""

    name = "Anthropic"
    type = "api"

    def __init__(self, api_key: str, model: str = "claude-3-5-sonnet-20241022") -> None:
        self.api_key = api_key
        self.model = model
        self.client = Anthropic(api_key=api_key)

    def test_connection(self) -> bool:
        """Test API connection."""
        try:
            # Simple API call to verify key
            self.client.messages.create(
                model=self.model, max_tokens=10, messages=[{"role": "user", "content": "Hi"}]
            )
            return True
        except Exception as e:
            Logger.error("Anthropic connection test failed", e)
            return False

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

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

        try:
            response = self.client.messages.create(
                model=self.model,
                max_tokens=4000,
                system=system_prompt,
                messages=[{"role": "user", "content": user_input}],
                temperature=0.7,
            )

            return response.content[0].text if response.content else ""

        except Exception as e:
            Logger.error("Anthropic execution failed", e)
            raise RuntimeError(f"Anthropic API 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

    @staticmethod
    def get_available_models(api_key: str) -> list[dict]:
        """Get list of available models from API."""
        try:
            # Anthropic doesn't have a models list API yet, return known models
            return [
                {
                    "id": "claude-3-5-sonnet-20241022",
                    "name": "Claude 3.5 Sonnet",
                    "description": "Most capable and intelligent",
                },
                {
                    "id": "claude-3-opus-20240229",
                    "name": "Claude 3 Opus",
                    "description": "Powerful for complex tasks",
                },
                {
                    "id": "claude-3-sonnet-20240229",
                    "name": "Claude 3 Sonnet",
                    "description": "Balanced performance",
                },
                {
                    "id": "claude-3-haiku-20240307",
                    "name": "Claude 3 Haiku",
                    "description": "Fast and efficient",
                },
            ]
        except Exception:
            # Return fallback if API key check fails
            return [
                {
                    "id": "claude-3-5-sonnet-20241022",
                    "name": "Claude 3.5 Sonnet",
                    "description": "Most capable and intelligent",
                },
                {
                    "id": "claude-3-opus-20240229",
                    "name": "Claude 3 Opus",
                    "description": "Powerful for complex tasks",
                },
            ]
