"""
OpenAI 提供商
"""
import os
from typing import Optional

from loguru import logger

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


class OpenAIProvider(BaseLLMProvider):
    """OpenAI 提供商"""

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

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

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

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

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

            logger.debug(f"调用 OpenAI API: model={self.config.openai_model}")
            response = client.chat.completions.create(
                model=self.config.openai_model,
                messages=messages,
                temperature=self.config.temperature,
                max_tokens=self.config.max_tokens,
            )

            return LLMResponse(
                content=response.choices[0].message.content,
                success=True,
                tokens_used=response.usage.total_tokens,
            )
        except Exception as e:
            logger.error(f"OpenAI API 调用失败: {e}")
            return LLMResponse(content="", success=False, error=str(e))

    async def is_available(self) -> bool:
        """检查 OpenAI API 是否可用"""
        api_key = self.config.openai_api_key or os.environ.get("OPENAI_API_KEY")
        if not api_key:
            return False
        try:
            from openai import OpenAI
            return True
        except ImportError:
            return False
