"""
业务API客户端 - 统一处理与DSP业务系统的HTTP交互
"""
from typing import Dict, Any, Optional, Union
import httpx
from loguru import logger

from mcp_framework.config.settings import settings

class DspApiClient:
    """DSP业务API客户端"""
    
    def __init__(self):
        self.base_url = settings.get("BUSINESS_API_BASE_URL", "https://openapi.growone.sg")
        self.api_version = settings.get("BUSINESS_API_VERSION", "v1")
        self.access_token = settings.get("BUSINESS_API_ACCESS_TOKEN", "")
        self.timeout = float(settings.get("BUSINESS_API_TIMEOUT", 30.0))
        
        # 服务标识符 - 用于构建URL
        self.service_id = "mcp"  # 可以从配置读取
        
        # 验证基础URL格式
        if not self.base_url.startswith(("http://", "https://")):
            self.base_url = f"https://{self.base_url}"
        if self.base_url.endswith("/"):
            self.base_url = self.base_url[:-1]
            
    def _build_url(self, module: str, function: str) -> str:
        """构建API URL
        
        Args:
            module: 模块名，如 'market', 'engine', 'planFlowInfos'
            function: 功能名，如 'accounts/list', 'plans/get'
            
        Returns:
            完整的API URL
        """
        # 常规模块请求
        return f"{self.base_url}/{self.service_id}/{self.api_version}/{module}/{function}"
    
    def _get_headers(self) -> Dict[str, str]:
        """获取请求头，包含鉴权信息"""
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
        
        # 添加鉴权token（如果存在）
        if self.access_token:
            headers["Access-Token"] = self.access_token
            
        return headers
    
    async def request(
        self, 
        module: str, 
        function: str, 
        params: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        发送请求到业务API
        
        Args:
            module: 模块名，如 'market', 'engine'
            function: 功能名，如 'accounts/list', 'plans/get'
            params: 请求参数（JSON格式）
            
        Returns:
            API响应内容
        """
        url = self._build_url(module, function)
        headers = self._get_headers()
        
        try:
            logger.debug(f"发送请求到DSP API: {url}")
            logger.debug(f"请求参数: {params}")
            
            async with httpx.AsyncClient() as client:
                # 统一使用POST方法
                response = await client.post(
                    url,
                    json=params,
                    headers=headers,
                    timeout=self.timeout
                )
                
                # 尝试解析响应
                response_data = response.json()
                logger.debug(f"DSP API {url}响应: {response_data}")
                
                # 检查业务状态码
                if response_data.get("code") != 0:
                    error_msg = response_data.get("message", "未知错误")
                    logger.error(f"DSP API错误: {error_msg}, code={response_data.get('code')}")
                    return {
                        "success": False,
                        "error": error_msg,
                        "code": response_data.get("code"),
                        "data": response_data.get("data")
                    }
                
                # 成功响应
                return {
                    "success": True,
                    "data": response_data.get("data"),
                    "message": response_data.get("message", "成功"),
                    "total": response_data.get("total"),
                    "code": response_data.get("code")
                    # 可以添加其他业务级别的元数据
                }
                
        except httpx.RequestError as e:
            logger.error(f"请求DSP API错误: {str(e)}")
            return {
                "success": False,
                "error": f"网络请求错误: {str(e)}",
                "code": -1
            }
        except Exception as e:
            logger.error(f"处理DSP API响应错误: {str(e)}")
            return {
                "success": False,
                "error": f"处理响应错误: {str(e)}",
                "code": -2
            }

# 创建全局API客户端实例
api_client = DspApiClient() 