"""
Business API configuration utility functions.

This module provides utilities for fetching and processing business API configurations.
"""

import json
import os
import requests
from typing import Dict, List, Any
from ..util.logger_config import get_logger

# 配置日志
logger = get_logger(__name__)




def get_business_api_details(api_ids: List[int], auth_token: str = None) -> List[Dict[str, Any]]:
    """
    获取业务平台API详情

    调用业务平台接口获取指定API ID列表的详细信息

    Args:
        api_ids: API ID列表，例如 [1925128743899111425, 1925128744524062721]
        auth_token: 认证token，如果不提供则使用默认token

    Returns:
        List[Dict[str, Any]]: API详情列表，返回接口响应中的data字段内容

    Raises:
        requests.RequestException: 当网络请求失败时抛出
        ValueError: 当响应格式不正确或返回错误时抛出

    Example:
        >>> api_ids = [1925128743899111425, 1925128744524062721]
        >>> details = get_business_api_details(api_ids)
        >>> print(len(details))
        2
    """
    if not isinstance(api_ids, list) or not api_ids:
        raise ValueError("api_ids must be a non-empty list")

    # 默认认证token
    default_token = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImM3OGU0M2NlLTJhZjQtNGRjYy1iMWE1LTU3YjM5YTdkNTA1OSJ9.5f1lSJJdLUunZIwCfneT1DiagGN4jD-QCnFCffWmrnvEcLfpuSMWRpY7fF-6H3yZ2N5ICZ4ZQN6cx7iqwF6jKw"
    token = auth_token or default_token

    # 接口URL - 支持环境变量配置
    # 从环境变量获取基础URL，必须配置
    base_url = os.getenv("LZWCAI_CORP_MANAGER_URL",'http://lzwcai-demp-corp-manager:8086')
    if not base_url:
        raise ValueError("环境变量 LZWCAI_CORP_MANAGER_URL 未配置，请设置业务平台基础URL，例如: http://lzwcai-demp-corp-manager:8086")
    
    # API路径
    api_path = "/system/mcpServer/bizSys/api/getByIds"
    url = base_url.rstrip("/") + api_path

    # 请求头
    headers = {
        "Authorization": f"Bearer {token}",
        # "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
        "Content-Type": "application/json",
        # "Accept": "*/*",
        # "Host": "192.168.2.236:8088",
        "Connection": "keep-alive"
    }

    try:
        # 发送POST请求
        response = requests.post(url, headers=headers, json=api_ids, timeout=30)
        response.raise_for_status()  # 检查HTTP状态码

        # 解析响应JSON
        response_data = response.json()

        # 检查响应格式
        if not isinstance(response_data, dict):
            raise ValueError("响应格式不正确：期望JSON对象")

        # 检查业务状态码
        code = response_data.get("code")
        if code != 200:
            msg = response_data.get("msg", "未知错误")
            raise ValueError(f"业务接口返回错误：code={code}, msg={msg}")

        # 获取data字段
        data = response_data.get("data", [])
        if not isinstance(data, list):
            logger.warning("响应中的data字段不是列表类型，将转换为列表")
            data = [data] if data is not None else []

        logger.info(f"成功获取 {len(data)} 个API详情")
        return data

    except requests.exceptions.Timeout:
        raise requests.RequestException("请求超时：接口响应时间过长")
    except requests.exceptions.ConnectionError:
        raise requests.RequestException("连接错误：无法连接到业务平台服务器")
    except requests.exceptions.HTTPError as e:
        raise requests.RequestException(f"HTTP错误：{e}")
    except json.JSONDecodeError:
        raise ValueError("响应格式错误：无法解析JSON数据")
    except Exception as e:
        logger.error(f"获取API详情时发生未知错误：{str(e)}")
        raise


def map_api_details_to_config(api_details: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    将API详情数据映射为api_config.json格式

    Args:
        api_details: get_business_api_details方法返回的API详情列表

    Returns:
        Dict[str, Any]: 符合api_config.json格式的配置对象

    Raises:
        ValueError: 当输入数据格式不正确时抛出

    Example:
        >>> api_details = get_business_api_details([1925128743899111425])
        >>> config = map_api_details_to_config(api_details)
        >>> print(config["serverName"])
        lzwcai_mcp_api_converter
    """
    if not isinstance(api_details, list):
        raise ValueError("api_details must be a list")

    if not api_details:
        raise ValueError("api_details cannot be empty")

    # 获取第一个API的domainUrl作为全局domainUrl
    domain_url = ""
    if api_details and isinstance(api_details[0], dict):
        domain_url = api_details[0].get("domainUrl", "")

    # 收集所有businessPrompts用于生成description
    business_prompts = []
    for api in api_details:
        if isinstance(api, dict) and api.get("businessPrompts"):
            business_prompts.append(api["businessPrompts"])

    # 生成description
    description = "、".join(business_prompts) if business_prompts else "业务API集合"

    # 构建配置对象
    config = {
        "serverName": "lzwcai_mcp_api_converter",
        "description": description,
        "domainUrl": domain_url,
        "packageName": "lzwcai-mcp-dyntoolapi",
        "version": "1.0.0",
        "apiConfig": api_details  # 直接使用原始API详情数据
    }

    logger.info(f"成功映射 {len(api_details)} 个API到配置格式")
    logger.info(f"服务名称: {config['serverName']}")
    logger.info(f"域名URL: {config['domainUrl']}")
    logger.info(f"描述: {config['description']}")

    return config


def get_business_api_config(api_ids: List[int], auth_token: str = None) -> Dict[str, Any]:
    """
    一步到位获取业务平台API配置

    传入API ID列表，直接返回处理好的api_config.json格式配置

    Args:
        api_ids: API ID列表，例如 [1925128743899111425, 1925128744524062721]
        auth_token: 认证token，如果不提供则使用默认token

    Returns:
        Dict[str, Any]: 符合api_config.json格式的完整配置对象

    Raises:
        requests.RequestException: 当网络请求失败时抛出
        ValueError: 当响应格式不正确或返回错误时抛出

    Example:
        >>> api_ids = [1925128743899111425, 1925128744524062721]
        >>> config = get_business_api_config(api_ids)
        >>> print(config["serverName"])
        lzwcai_mcp_api_converter
        >>> print(len(config["apiConfig"]))
        2
    """
    try:
        # 步骤1: 获取API详情
        logger.info(f"开始获取 {len(api_ids)} 个API的详情...")
        api_details = get_business_api_details(api_ids, auth_token)

        # 步骤2: 映射为配置格式
        logger.info("开始映射为配置格式...")
        config = map_api_details_to_config(api_details)

        logger.info(f"[SUCCESS] 成功生成API配置！包含 {len(config['apiConfig'])} 个API")
        return config

    except Exception as e:
        logger.error(f"获取业务API配置时发生错误: {str(e)}")
        raise



