"""
OpenAI LLM 实现
"""
import os
import logging
from typing import Dict, Any, List, Optional
from openai import AsyncOpenAI
from openai._client import AsyncOpenAI

logger = logging.getLogger("llm.openai")


class OpenAILLM:
    """OpenAI LLM"""

    def __init__(self, model_name: str = "gpt-4", api_key: Optional[str] = None, base_url: Optional[str] = None):
        self.model_name = model_name
        # 优先使用传入的参数，否则使用环境变量
        self.api_key = api_key or os.getenv("OPENAI_API_KEY", "")
        self.base_url = base_url or os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")

        api_key_info = f"{self.api_key[:10]}..." if self.api_key else "None"
        logger.info(f"初始化 OpenAI LLM: model={model_name}, api_key={api_key_info}, base_url={self.base_url}")

        if not self.api_key:
            logger.warning("⚠️ WARNING: No API key provided!")

        # 配置超时
        self.client = AsyncOpenAI(
            api_key=self.api_key,
            base_url=self.base_url,
            timeout=60.0,  # 60秒超时
            max_retries=1  # 减少重试次数
        )

    async def decide(self, prompt: str) -> Dict[str, Any]:
        """
        LLM 决策 - 判断是否需要调用技能

        Args:
            prompt: 完整的 Prompt

        Returns:
            Dict: 包含 needs_skill, tool_calls, response 等
        """
        # 构建决策用的系统提示
        system_prompt = """你是一个智能助手。请分析用户请求，判断是否需要调用工具来回答问题。

如果需要调用工具，请按以下格式返回 JSON：
{
  "needs_skill": true,
  "tool_calls": [
    {"skill_id": "工具名称", "parameters": {"参数": "值"}, "reason": "调用原因"}
  ]
}

如果不需要调用工具，请返回：
{
  "needs_skill": false,
  "response": "直接回答用户的内容"
}

请只返回 JSON，不要其他内容。"""

        try:
            response = await self.client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_tokens=2000
            )

            content = response.choices[0].message.content

            # 尝试解析 JSON
            import json
            try:
                result = json.loads(content)
                return result
            except json.JSONDecodeError:
                # 解析失败，作为普通回复处理
                return {
                    "needs_skill": False,
                    "response": content
                }

        except Exception as e:
            return {
                "needs_skill": False,
                "response": f"LLM 调用失败: {str(e)}"
            }

    async def generate(self, prompt: str, tool_results: List[Dict]) -> str:
        """
        生成回复

        Args:
            prompt: 完整的 Prompt
            tool_results: 工具调用结果

        Returns:
            str: 生成的回复
        """
        messages = [{"role": "user", "content": prompt}]

        # 添加工具结果作为上下文
        if tool_results:
            for result in tool_results:
                if result.get("success"):
                    messages.append({
                        "role": "assistant",
                        "content": f"工具 {result.get('skill_id')} 返回: {result.get('result')}"
                    })

        try:
            response = await self.client.chat.completions.create(
                model=self.model_name,
                messages=messages,
                temperature=0.7,
                max_tokens=4000
            )

            return response.choices[0].message.content

        except Exception as e:
            return f"生成回复失败: {str(e)}"

    async def generate_stream(self, prompt: str, tool_results: List[Dict]):
        """
        流式生成回复

        Args:
            prompt: 完整的 Prompt
            tool_results: 工具调用结果

        Yields:
            str: 生成的回复片段
        """
        messages = [{"role": "user", "content": prompt}]

        # 添加工具结果作为上下文
        if tool_results:
            for result in tool_results:
                if result.get("success"):
                    messages.append({
                        "role": "assistant",
                        "content": f"工具 {result.get('skill_id')} 返回: {result.get('result')}"
                    })

        try:
            response = await self.client.chat.completions.create(
                model=self.model_name,
                messages=messages,
                temperature=0.7,
                max_tokens=4000,
                stream=True
            )

            async for chunk in response:
                if chunk.choices[0].delta.content:
                    yield chunk.choices[0].delta.content

        except Exception as e:
            yield f"生成回复失败: {str(e)}"
