#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
认证数据转换器
提供简洁的API来获取和转换认证信息
"""

import requests
import json
import sys
import os
from typing import Optional, Dict, Any

# 添加项目根目录到 Python 路径
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
sys.path.append(project_root)

from ..business.get_business_api import get_business_api_details
from ..util.logger_config import get_logger

# 配置日志
logger = get_logger(__name__)



class AuthDataTransformer:
    """认证数据转换器"""

    def __init__(self, base_url: str = None):
        """
        初始化转换器
        
        Args:
            base_url: API基础URL，如果不提供则从环境变量 LZWCAI_CORP_MANAGER_URL 获取
        """
        if base_url is None:
            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")
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        
        # 设置默认请求头
        self.session.headers.update({
            'User-Agent': 'Python-API-Client/1.0.0',
            'Accept': '*/*',
            'Connection': 'keep-alive'
        })

    def get_transformed_auth_data(self, user_id: str, business_system_id: str) -> Optional[Dict[Any, Any]]:
        """
        获取并转换认证数据
        
        Args:
            user_id: 用户ID
            business_system_id: 业务系统ID
            
        Returns:
            转换后的认证数据JSON，失败时返回None
        """
        try:
            # 1. 获取原始认证信息
            raw_data = self._get_raw_auth_info(user_id, business_system_id)
            if not raw_data:
                return None
            
            # 2. 处理bizSysConfig并获取API详情
            self._process_biz_sys_config(raw_data)
            
            # 3. 转换数据结构
            transformed_data = self._transform_data_structure(raw_data)
            
            return transformed_data
            
        except Exception as e:
            logger.error(f"获取转换认证数据时发生错误: {e}")
            return None

    def _get_raw_auth_info(self, user_id: str, business_system_id: str) -> Optional[Dict[Any, Any]]:
        """
        获取原始认证信息
        
        Args:
            user_id: 用户ID
            business_system_id: 业务系统ID
            
        Returns:
            原始API响应数据，失败时返回None
        """
        # url = f"{self.base_url}/system/mcpServer/auth/info/{user_id}/{business_system_id}"
        url = f"{self.base_url}/system/mcpServer/auth/info/{user_id}/{business_system_id}"
        
        try:
            response = self.session.get(url, timeout=30)
            
            if response.status_code == 200:
                try:
                    return response.json()
                except json.JSONDecodeError:
                    logger.error(f"响应不是有效的JSON格式: {response.text}")
                    return None
            else:
                logger.error(f"请求失败，状态码: {response.status_code}, 响应: {response.text}")
                return None
                
        except requests.exceptions.RequestException as e:
            logger.error(f"请求异常: {e}")
            return None

    def _process_biz_sys_config(self, response_data: Dict[Any, Any]) -> None:
        """
        处理bizSysConfig，解析loginApiId并获取API详情
        
        Args:
            response_data: API响应数据
        """
        try:
            data = response_data.get("data", {})
            if not data:
                return
            
            biz_sys_config_str = data.get("bizSysConfig")
            if not biz_sys_config_str:
                return
            
            try:
                biz_sys_config = json.loads(biz_sys_config_str)
                login_api_id = biz_sys_config.get("loginApiId")
                logger.info(f"登录APIID: {login_api_id}")
                logger.debug(f"获取API详情...", get_business_api_details)
                if login_api_id and get_business_api_details:
                    try:
                        api_details = get_business_api_details([int(login_api_id)])
                        logger.debug(f"API详情: {api_details}")
                        if api_details and len(api_details) > 0:
                            data["apiItemDetail"] = api_details[0]
                    except Exception as e:
                        logger.error(f"获取API详情时发生错误: {e}")
                        
            except json.JSONDecodeError as e:
                logger.error(f"解析bizSysConfig JSON失败: {e}")
                
        except Exception as e:
            logger.error(f"处理bizSysConfig时发生错误: {e}")

    def _transform_data_structure(self, result: Dict[Any, Any]) -> Optional[Dict[Any, Any]]:
        """
        将原始数据结构转换为新的数据结构
        
        Args:
            result: 原始数据
            
        Returns:
            转换后的新数据结构，失败时返回None
        """
        try:
            data = result.get("data", {})
            if not data:
                return None
            
            # 解析userAuthConfig
            user_auth_config = self._safe_json_parse(data.get("userAuthConfig", "{}"))
            
            # 解析bizSysConfig
            biz_sys_config = self._safe_json_parse(data.get("bizSysConfig", "{}"))
            
            # 获取apiItemDetail
            api_item_detail = data.get("apiItemDetail", {})
            
            # 构建新的数据结构
            new_data = {
                "authType": user_auth_config.get("authType"),
                "name": biz_sys_config.get("name"),
                "apiKey": user_auth_config.get("apiKey"),
                "apiVO": self._build_api_vo(user_auth_config, biz_sys_config, api_item_detail)
            }
            
            return {
                "code": result.get("code", 200),
                "msg": result.get("msg", "成功"),
                "data": new_data
            }
            
        except Exception as e:
            logger.error(f"转换数据结构时发生错误: {e}")
            return None

    def _safe_json_parse(self, json_str: str) -> Dict[Any, Any]:
        """
        安全解析JSON字符串
        
        Args:
            json_str: JSON字符串
            
        Returns:
            解析后的字典，失败时返回空字典
        """
        try:
            return json.loads(json_str) if json_str else {}
        except json.JSONDecodeError:
            return {}

    def _build_api_vo(self, user_auth_config: Dict[Any, Any], biz_sys_config: Dict[Any, Any], api_item_detail: Dict[Any, Any]) -> Optional[Dict[Any, Any]]:
        """
        构建apiVO对象

        Args:
            user_auth_config: 用户认证配置
            biz_sys_config: 业务系统配置
            api_item_detail: API详情

        Returns:
            apiVO对象
        """
        if not biz_sys_config:
            return None

        # 获取dynamicValues和paramMappings
        dynamic_values = user_auth_config.get("dynamicValues", {})
        account_config = biz_sys_config.get("accountConfig", {})
        param_mappings = account_config.get("paramMappings", [])

        # 预处理accountConfig - 构建为对象然后转换为JSON字符串
        processed_account_config = {}
        if param_mappings:
            processed_account_config = {"parametersBody": []}

            for param_mapping in param_mappings:
                param_name = param_mapping.get("paramName")
                if param_name:
                    param_value = dynamic_values.get(param_name, param_mapping.get("defaultValue", ""))

                    processed_account_config["parametersBody"].append({
                        "paramName": param_name,
                        "defaultValue": param_value,
                        "requestType": param_mapping.get("requestType", "form")
                    })

        # 构建tcapabilityApiVO
        tcapability_api_vo = self._build_tcapability_api_vo(api_item_detail)

        return {
            "accountConfig": json.dumps(processed_account_config, ensure_ascii=False),  # 转换为JSON字符串
            "tokenPath": biz_sys_config.get("tokenPath"),
            "tcapabilityApiVO": tcapability_api_vo  # 放在apiVO里面
        }

    def _build_tcapability_api_vo(self, api_item_detail: Dict[Any, Any]) -> Optional[Dict[Any, Any]]:
        """
        构建tcapabilityApiVO对象
        
        Args:
            api_item_detail: API详情
            
        Returns:
            tcapabilityApiVO对象
        """
        if not api_item_detail:
            return None
            
        # 复制API详情并重命名parameters为apiParameterList
        tcapability_api_vo = api_item_detail.copy()
        if "parameters" in tcapability_api_vo:
            tcapability_api_vo["apiParameterList"] = tcapability_api_vo.pop("parameters")
        
        return tcapability_api_vo


# 便捷函数
def get_auth_data(user_id: str, business_system_id: str, base_url: str = None) -> Optional[Dict[Any, Any]]:
    """
    便捷函数：获取转换后的认证数据
    
    Args:
        user_id: 用户ID
        business_system_id: 业务系统ID
        base_url: API基础URL，如果不提供则从环境变量 LZWCAI_CORP_MANAGER_URL 获取
        
    Returns:
        转换后的认证数据JSON，失败时返回None
        
    Example:
        >>> auth_data = get_auth_data("447", "1952255539442741249")
        >>> if auth_data:
        ...     print(f"认证类型: {auth_data['data']['authType']}")
    """
    transformer = AuthDataTransformer(base_url)
    return transformer.get_transformed_auth_data(user_id, business_system_id)


if __name__ == "__main__":
    # 测试代码
    from ..util.logger_config import setup_logging
    import logging
    setup_logging(log_level=logging.INFO)
    result = get_auth_data("447", "1957354824118095874")
    if result:
        logger.info("=== 转换后的认证数据 ===")
        logger.info(json.dumps(result, indent=2, ensure_ascii=False))
    else:
        logger.error("获取认证数据失败")
