"""
Anthropic Claude模型实现
"""
from typing import List, Optional, AsyncIterator
from anthropic import AsyncAnthropic
from ..base import BaseAIModel, Message, ModelConfig


class AnthropicModel(BaseAIModel):
    """Anthropic Claude模型实现"""
    
    def __init__(self, config: ModelConfig):
        super().__init__(config)
        self.client = AsyncAnthropic(
            api_key=config.api_key,
            base_url=config.api_base,
            timeout=config.timeout
        )
    
    async def chat(
        self,
        messages: List[Message],
        tools: Optional[List[dict]] = None,
        **kwargs
    ) -> Message:
        """同步对话"""
        # 分离system消息
        system_message = None
        formatted_messages = []
        
        for msg in messages:
            if msg.role == "system":
                system_message = msg.content
            else:
                formatted_messages.append({
                    "role": msg.role,
                    "content": msg.content
                })
        
        params = {
            "model": self.config.model_name,
            "messages": formatted_messages,
            "max_tokens": self.config.max_tokens,
            "temperature": self.config.temperature,
        }
        
        if system_message:
            params["system"] = system_message
        
        if tools:
            params["tools"] = tools
        
        params.update(kwargs)
        
        response = await self.client.messages.create(**params)
        
        content = ""
        tool_calls = []
        
        for block in response.content:
            if block.type == "text":
                content += block.text
            elif block.type == "tool_use":
                tool_calls.append({
                    "id": block.id,
                    "type": "function",
                    "function": {
                        "name": block.name,
                        "arguments": block.input
                    }
                })
        
        return Message(
            role="assistant",
            content=content,
            tool_calls=tool_calls if tool_calls else None
        )
    
    async def chat_stream(
        self,
        messages: List[Message],
        tools: Optional[List[dict]] = None,
        **kwargs
    ) -> AsyncIterator[str]:
        """流式对话"""
        system_message = None
        formatted_messages = []
        
        for msg in messages:
            if msg.role == "system":
                system_message = msg.content
            else:
                formatted_messages.append({
                    "role": msg.role,
                    "content": msg.content
                })
        
        params = {
            "model": self.config.model_name,
            "messages": formatted_messages,
            "max_tokens": self.config.max_tokens,
            "temperature": self.config.temperature,
            "stream": True,
        }
        
        if system_message:
            params["system"] = system_message
        
        if tools:
            params["tools"] = tools
        
        params.update(kwargs)
        
        async with self.client.messages.stream(**params) as stream:
            async for text in stream.text_stream:
                yield text
    
    async def embed(self, text: str) -> List[float]:
        """文本嵌入（Anthropic不直接提供，需要使用其他服务）"""
        raise NotImplementedError("Anthropic不提供嵌入API，请使用OpenAI或其他服务")
