"""AI 服务 - 统一的 AI 供应商接口"""

import re
from typing import AsyncIterator, Dict, List, Optional

from openai import AsyncOpenAI

from ..models.schemas import AIProvider, ChatMessage, Live2DParams


class AIService:
    """AI 服务，使用 OpenAI SDK 统一接口"""

    def __init__(self, providers: Dict[str, AIProvider]):
        self.providers = providers
        self.clients: Dict[str, AsyncOpenAI] = {}
        self._init_clients()

    def _init_clients(self):
        """初始化所有启用的 AI 客户端"""
        for provider_id, provider in self.providers.items():
            if provider.enabled and provider.api_key:
                self.clients[provider_id] = AsyncOpenAI(
                    api_key=provider.api_key, base_url=provider.base_url
                )

    def get_default_provider(self) -> tuple[str, AIProvider]:
        """获取默认供应商"""
        for provider_id, provider in self.providers.items():
            if provider.enabled:
                return provider_id, provider
        raise ValueError("没有可用的 AI 供应商")

    def get_provider(self, provider_id: Optional[str] = None) -> tuple[str, AIProvider]:
        """获取指定供应商，如果未指定则返回默认供应商"""
        if provider_id:
            if provider_id not in self.providers:
                raise ValueError(f"供应商不存在: {provider_id}")
            provider = self.providers[provider_id]
            if not provider.enabled:
                raise ValueError(f"供应商未启用: {provider_id}")
            return provider_id, provider

        return self.get_default_provider()

    async def chat_completion(
        self,
        messages: List[ChatMessage],
        provider_id: Optional[str] = None,
        model: Optional[str] = None,
        stream: bool = True,
    ) -> AsyncIterator[str]:
        """聊天完成（流式或非流式）"""
        provider_id, provider = self.get_provider(provider_id)
        client = self.clients.get(provider_id)

        if not client:
            raise ValueError(f"供应商客户端未初始化: {provider_id}")

        # 使用指定模型或默认模型
        model_name = model or provider.default_model

        # 转换消息格式
        openai_messages = [{"role": msg.role, "content": msg.content} for msg in messages]

        # 调用 OpenAI API
        response = await client.chat.completions.create(
            model=model_name,
            messages=openai_messages,
            max_tokens=provider.max_tokens,
            temperature=provider.temperature,
            stream=stream,
        )

        if stream:
            # 流式响应
            async for chunk in response:
                if chunk.choices and chunk.choices[0].delta.content:
                    yield chunk.choices[0].delta.content
        else:
            # 非流式响应
            if response.choices:
                yield response.choices[0].message.content

    def generate_live2d_params(self, text: str) -> Live2DParams:
        """根据文本内容生成 Live2D 参数"""
        params = Live2DParams()

        # 简单规则：根据关键词和标点符号推断表情
        text_lower = text.lower()

        # 开心/笑容
        if any(word in text_lower for word in ["开心", "笑", "哈哈", "😊", "😄", "高兴", "快乐"]):
            params.eye_smile = 0.8
            params.mouth_smile = 0.9
            params.mouth_open = 0.3

        # 惊讶/疑问
        elif any(word in text_lower for word in ["啊", "哦", "哇", "！", "?"]) or text.endswith("?"):
            params.eye_open = 1.0
            params.mouth_open = 0.6
            if "?" in text:
                params.head_tilt = 0.2

        # 思考
        elif any(word in text_lower for word in ["嗯", "让我想想", "思考", "🤔"]):
            params.eye_open = 0.6
            params.head_tilt = -0.15
            params.mouth_open = 0.1

        # 悲伤/担心
        elif any(word in text_lower for word in ["难过", "伤心", "抱歉", "对不起", "😢"]):
            params.eye_open = 0.5
            params.eye_smile = 0.0
            params.mouth_smile = 0.0
            params.head_tilt = -0.1

        # 默认表情（自然状态）
        else:
            params.eye_open = 0.9
            params.eye_smile = 0.3
            params.mouth_open = 0.2
            params.mouth_smile = 0.4

        return params

    def reload_providers(self, providers: Dict[str, AIProvider]):
        """重新加载供应商配置（热重载）"""
        self.providers = providers
        self.clients.clear()
        self._init_clients()
