"""
Anthropic Claude 提供商
"""
import os
from typing import Optional

from loguru import logger

from .base import BaseLLMProvider, LLMResponse
from ..types import LLMConfig


class ClaudeProvider(BaseLLMProvider):
    """Anthropic Claude 提供商"""

    def __init__(self, config: LLMConfig):
        self.config = config
        self._client = None

    def _get_client(self):
        """获取 Anthropic 客户端"""
        if self._client is None:
            try:
                import anthropic
                api_key = self.config.claude_api_key or os.environ.get("ANTHROPIC_API_KEY")
                if not api_key:
                    raise ValueError("未配置 Claude API Key，请设置 ANTHROPIC_API_KEY 环境变量或传入 claude_api_key 参数")
                self._client = anthropic.Anthropic(api_key=api_key)
            except ImportError:
                raise ImportError("请安装 anthropic 包: pip install anthropic")
        return self._client

    async def call(self, prompt: str, system_prompt: Optional[str] = None) -> LLMResponse:
        """
        调用 Claude API

        Args:
            prompt: 用户提示
            system_prompt: 系统提示

        Returns:
            LLMResponse: 响应结果
        """
        try:
            client = self._get_client()
            kwargs = {
                "model": self.config.claude_model,
                "max_tokens": self.config.max_tokens,
                "messages": [{"role": "user", "content": prompt}],
            }
            if system_prompt:
                kwargs["system"] = system_prompt

            logger.debug(f"调用 Claude API: model={self.config.claude_model}")
            response = client.messages.create(**kwargs)

            return LLMResponse(
                content=response.content[0].text,
                success=True,
                tokens_used=response.usage.input_tokens + response.usage.output_tokens,
            )
        except Exception as e:
            logger.error(f"Claude API 调用失败: {e}")
            return LLMResponse(content="", success=False, error=str(e))

    async def is_available(self) -> bool:
        """检查 Claude API 是否可用"""
        api_key = self.config.claude_api_key or os.environ.get("ANTHROPIC_API_KEY")
        if not api_key:
            return False
        try:
            import anthropic
            return True
        except ImportError:
            return False
