"""
自定义 LLM 提供商
支持用户传入自定义调用函数
"""
from typing import Optional

from loguru import logger

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


class CustomProvider(BaseLLMProvider):
    """自定义 LLM 提供商"""

    def __init__(self, config: LLMConfig):
        self.config = config
        self.call_fn = config.custom_call_fn

    async def call(self, prompt: str, system_prompt: Optional[str] = None) -> LLMResponse:
        """
        调用自定义函数

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

        Returns:
            LLMResponse: 响应结果
        """
        if self.call_fn is None:
            return LLMResponse(content="", success=False, error="未配置自定义调用函数")

        try:
            # 组合提示
            full_prompt = f"{system_prompt}\n\n{prompt}" if system_prompt else prompt

            logger.debug("调用自定义 LLM 函数")
            result = self.call_fn(full_prompt)

            # 确保返回字符串
            if not isinstance(result, str):
                result = str(result)

            return LLMResponse(content=result, success=True)
        except Exception as e:
            logger.error(f"自定义 LLM 调用失败: {e}")
            return LLMResponse(content="", success=False, error=str(e))

    async def is_available(self) -> bool:
        """检查自定义函数是否可用"""
        return self.call_fn is not None
