"""
API认证服务模块

提供用户认证、Token管理、企业认证等功能
"""

import asyncio
import json
import os
import random
import sys
from typing import Any, Dict, List, Optional, Tuple, Union

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

from ..business.business_util import create_structured_data, generate_api_array
from ..util.nested_value import get_nested_value
from ..util.logger_config import get_logger
from .get_auth import get_auth_data

# 获取日志器
logger = get_logger(__name__)


class AuthError(Exception):
    """认证相关异常"""

    def __init__(self, message: str, error_code: Optional[str] = None):
        super().__init__(message)
        self.error_code = error_code


class AuthConfig:
    """认证配置类"""

    # Token相关配置
    TOKEN_PREFIX = "lzwc"
    TOKEN_SUFFIX = "token"

    # 重试配置
    DEFAULT_MAX_ATTEMPTS = 3
    DEFAULT_BASE_DELAY = 1
    DEFAULT_MAX_DELAY = 60


class ParameterExtractor:
    """参数提取器"""

    @staticmethod
    def extract_param_defaults(param_list: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        将参数列表转换为 {paramName: defaultValue} 的字典

        Args:
            param_list: 参数字典列表，每个元素包含 paramName 和 defaultValue

        Returns:
            以 paramName 为 key，defaultValue 为 value 的字典
        """
        if not isinstance(param_list, list):
            logger.warning(f"参数列表类型错误，期望list，实际{type(param_list)}")
            return {}

        logger.debug(f"提取参数默认值，参数数量: {len(param_list)}")
        result = {}

        for item in param_list:
            if not isinstance(item, dict):
                logger.warning(f"参数项类型错误，跳过: {item}")
                continue

            param_name = item.get("paramName")
            if param_name:
                default_value = item.get("defaultValue")
                result[param_name] = default_value
                logger.debug(f"参数 {param_name}: {default_value}")

        logger.debug(f"提取完成，共 {len(result)} 个参数")
        return result


class ApiRetryExecutor:
    """API重试执行器"""

    def __init__(
        self,
        max_attempts: int = AuthConfig.DEFAULT_MAX_ATTEMPTS,
        base_delay: int = AuthConfig.DEFAULT_BASE_DELAY,
        max_delay: int = AuthConfig.DEFAULT_MAX_DELAY,
    ):
        self.max_attempts = max_attempts
        self.base_delay = base_delay
        self.max_delay = max_delay

    async def execute_with_retry(
        self,
        api_config: Dict[str, Any],
        user_params: Dict[str, Any],
        need_auth: bool = False,
    ) -> Optional[Dict[str, Any]]:
        """
        使用指数退避策略的API调用重试

        Args:
            api_config: API配置信息
            user_params: 用户提供的参数
            need_auth: 是否需要鉴权

        Returns:
            API调用响应

        Raises:
            AuthError: 认证相关错误
        """
        from .core_server import call_api

        attempt = 0
        last_error = None

        while attempt < self.max_attempts:
            attempt += 1
            try:
                logger.info(f"尝试调用API，第 {attempt} 次")

                # 准备API调用数据
                api_array = generate_api_array([api_config])
                call_api_data = create_structured_data(
                    api_array[0]["schema"], user_params
                )

                # 执行API调用
                api_res = await call_api(api_config, call_api_data, need_auth=need_auth)

                # 检查响应是否包含错误
                if api_res and "error" not in api_res:
                    logger.info(f"API调用成功，第 {attempt} 次尝试")
                    return api_res

                # 记录错误信息
                error_msg = api_res.get("error", "未知错误") if api_res else "响应为空"
                logger.warning(f"API调用返回错误: {error_msg}")
                last_error = error_msg

                # 如果还有重试机会，等待后重试
                if attempt < self.max_attempts:
                    await self._wait_for_retry(attempt)

            except Exception as e:
                error_msg = str(e)
                logger.error(f"API调用发生异常: {error_msg}")
                last_error = error_msg

                if attempt < self.max_attempts:
                    await self._wait_for_retry(attempt)
                else:
                    logger.error(
                        f"API调用失败，已达到最大重试次数 ({self.max_attempts})"
                    )
                    raise AuthError(f"API调用失败: {error_msg}")

        # 所有重试都失败了
        raise AuthError(
            f"API调用失败，重试{self.max_attempts}次后仍然失败: {last_error}"
        )

    async def _wait_for_retry(self, attempt: int) -> None:
        """等待重试的延迟逻辑"""
        # 计算延迟时间（指数退避策略）
        delay = min(self.base_delay * (2 ** (attempt - 1)), self.max_delay)
        # 添加随机抖动（0.5-1.5倍）避免同时重试
        jitter = 0.5 + random.random()
        sleep_time = delay * jitter

        logger.info(f"等待 {sleep_time:.2f} 秒后进行第 {attempt + 1} 次重试")
        await asyncio.sleep(sleep_time)


class EnvironmentManager:
    """环境变量管理器，提供环境变量的增删改查功能，支持持久化存储"""
    
    _env_file = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../", ".env_lzwcai_mcp_api_converter"))

    @staticmethod
    def _load_persistent_tokens() -> Dict[str, str]:
        """从.env文件加载持久化的token"""
        tokens = {}
        try:
            if os.path.exists(EnvironmentManager._env_file):
                with open(EnvironmentManager._env_file, 'r', encoding='utf-8') as f:
                    for line in f:
                        line = line.strip()
                        if line and '=' in line and not line.startswith('#'):
                            key, value = line.split('=', 1)
                            key = key.strip()
                            value = value.strip()
                            if key:  # 确保key不为空
                                tokens[key] = value
        except Exception as e:
            logger.error(f"加载.env文件失败: {e}")
        return tokens

    @staticmethod
    def _save_persistent_tokens(tokens: Dict[str, str]) -> bool:
        """保存token到.env文件"""
        try:
            os.makedirs(os.path.dirname(EnvironmentManager._env_file), exist_ok=True)
            with open(EnvironmentManager._env_file, 'w', encoding='utf-8') as f:
                for key, value in tokens.items():
                    f.write(f"{key}={value}\n")
            return True
        except Exception as e:
            logger.error(f"保存.env文件失败: {e}")
            return False

    @staticmethod
    def get(key: str, default: Optional[str] = None) -> Optional[str]:
        """
        获取环境变量值，优先从进程环境变量获取，然后从持久化文件获取

        Args:
            key: 环境变量名
            default: 默认值

        Returns:
            环境变量值或默认值
        """
        # 先从进程环境变量获取
        value = os.environ.get(key)
        if value is not None:
            return value
            
        # 从持久化文件获取
        if key.endswith('token'):  # 只对token类型的环境变量使用持久化
            persistent_tokens = EnvironmentManager._load_persistent_tokens()
            value = persistent_tokens.get(key)
            if value is not None:
                # 同时设置到进程环境变量中
                os.environ[key] = value
                return value
                
        return default

    @staticmethod
    def set(key: str, value: str) -> bool:
        """
        设置环境变量，同时持久化token类型的变量

        Args:
            key: 环境变量名
            value: 环境变量值

        Returns:
            设置是否成功
        """
        try:
            # 设置到进程环境变量
            os.environ[key] = str(value)
            
            # 如果是token类型，同时持久化到文件
            if key.endswith('token'):
                persistent_tokens = EnvironmentManager._load_persistent_tokens()
                persistent_tokens[key] = str(value)
                if not EnvironmentManager._save_persistent_tokens(persistent_tokens):
                    logger.warning(f"持久化token失败，但进程环境变量已设置: {key}")
                else:
                    logger.debug(f"成功持久化token: {key}")
            
            logger.debug(f"成功设置环境变量: {key}")
            return True
        except Exception as e:
            logger.error(f"设置环境变量失败: {key}, 错误: {e}")
            return False

    @staticmethod
    def exists(key: str) -> bool:
        """
        检查环境变量是否存在

        Args:
            key: 环境变量名

        Returns:
            是否存在
        """
        # 先检查进程环境变量
        if key in os.environ:
            return True
            
        # 检查持久化文件
        if key.endswith('token'):
            persistent_tokens = EnvironmentManager._load_persistent_tokens()
            return key in persistent_tokens
            
        return False

    @staticmethod
    def delete(key: str) -> bool:
        """
        删除环境变量，同时删除持久化的token

        Args:
            key: 环境变量名

        Returns:
            删除是否成功
        """
        try:
            # 从进程环境变量删除
            if key in os.environ:
                del os.environ[key]
                
            # 如果是token类型，同时从持久化文件删除
            if key.endswith('token'):
                persistent_tokens = EnvironmentManager._load_persistent_tokens()
                if key in persistent_tokens:
                    del persistent_tokens[key]
                    EnvironmentManager._save_persistent_tokens(persistent_tokens)
                    logger.debug(f"成功删除持久化token: {key}")
                    
            logger.debug(f"成功删除环境变量: {key}")
            return True
        except Exception as e:
            logger.error(f"删除环境变量失败: {key}, 错误: {e}")
            return False


class TokenManager:
    """Token管理器"""

    def __init__(self):
        self.logger = get_logger("TokenManager")

    def generate_token_name(self, user_id: str, biz_sys_id: str) -> str:
        """
        生成Token名称

        Args:
            user_id: 用户ID
            biz_sys_id: 业务系统ID

        Returns:
            Token名称
        """
        return (
            f"{AuthConfig.TOKEN_PREFIX}{user_id}{biz_sys_id}{AuthConfig.TOKEN_SUFFIX}"
        )

    def check_token_exists(
        self, token_name: str
    ) -> Tuple[bool, Optional[Union[str, Dict[str, Any]]]]:
        """
        检查环境变量中是否存在Token，并返回反序列化后的值

        Args:
            token_name: Token名称

        Returns:
            (是否存在, Token值)
        """
        token_value = EnvironmentManager.get(token_name)
        if token_value is None:
            return False, None

        # 尝试反序列化Token值
        deserialized_value = self._deserialize_token_value(token_value, token_name)
        return True, deserialized_value

    def _deserialize_token_value(
        self, token_value: str, token_name: str
    ) -> Union[str, Dict[str, Any]]:
        """反序列化Token值"""
        try:
            # 尝试将JSON字符串反序列化为原始结构（字典）
            return json.loads(token_value)
        except json.JSONDecodeError:
            self.logger.debug(f"Token不是JSON格式，保留原始字符串: {token_name}")

            # 尝试处理字符串表示的字典，如 "{'key': 'value'}"
            if token_value.startswith("{") and token_value.endswith("}"):
                try:
                    import ast

                    return ast.literal_eval(token_value)
                except (ValueError, SyntaxError):
                    self.logger.debug(f"无法解析字典字符串: {token_value}")

            # 返回原始字符串
            return token_value

    def store_token(self, token_name: str, token_value: Any) -> bool:
        """
        存储Token到环境变量，自动序列化复杂结构

        Args:
            token_name: Token名称
            token_value: Token值

        Returns:
            存储是否成功
        """
        if token_value is None:
            self.logger.warning(f"Token值为None，不进行存储: {token_name}")
            return False

        # 序列化Token值
        serialized_value = self._serialize_token_value(token_value, token_name)
        if serialized_value is None:
            return False

        # 存储到环境变量
        success = EnvironmentManager.set(token_name, serialized_value)
        if success:
            self.logger.info(f"成功将Token存储到环境变量: {token_name}")
        else:
            self.logger.error(f"存储Token到环境变量失败: {token_name}")

        return success

    def _serialize_token_value(
        self, token_value: Any, token_name: str
    ) -> Optional[str]:
        """序列化Token值"""
        try:
            if isinstance(token_value, (dict, list)):
                return json.dumps(token_value)
            elif isinstance(token_value, bytes):
                return token_value.decode("utf-8")
            elif isinstance(token_value, (int, float, str)):
                return str(token_value)
            else:
                self.logger.error(
                    f"不支持的Token类型: {type(token_value)}，不进行存储: {token_name}"
                )
                return None
        except Exception as e:
            self.logger.error(f"序列化Token时出错: {str(e)}")
            return None


class CompanyAuthClient:
    """企业认证客户端 - 现在使用get_auth_data方法替代HTTP API调用"""

    def __init__(self):
        self.logger = get_logger("CompanyAuthClient")

    async def get_auth_info(
        self, user_id: str, biz_sys_id: str
    ) -> Tuple[Optional[int], Optional[Dict[str, Any]]]:
        """
        获取鉴权类型和认证数据

        Args:
            user_id: 用户ID
            biz_sys_id: 业务系统ID

        Returns:
            (鉴权类型, 认证数据)
        """
        try:
            self.logger.debug(f"使用get_auth_data获取认证信息: user_id={user_id}, biz_sys_id={biz_sys_id}")

            # 使用get_auth_data方法获取认证数据
            result = get_auth_data(user_id, biz_sys_id)

            if not result:
                self.logger.error("get_auth_data返回空结果")
                return None, None

            return self._parse_auth_response(result, user_id, biz_sys_id)

        except Exception as e:
            self.logger.error(f"获取鉴权类型失败: {str(e)}")
            return None, None

    def _parse_auth_response(
        self, result: Dict[str, Any], user_id: str, biz_sys_id: str
    ) -> Tuple[Optional[int], Optional[Dict[str, Any]]]:
        """解析认证响应"""
        if result.get("code") != 200:
            error_msg = result.get("msg", "未知错误")
            self.logger.error(f"获取鉴权类型失败: {error_msg}")
            return None, None

        auth_data = result.get("data", {})
        auth_type = auth_data.get("authType")

        # 将字符串类型的authType转换为整数
        auth_type_int = None
        if auth_type is not None:
            try:
                auth_type_int = int(auth_type)
                self.logger.info(
                    f"用户{user_id}业务系统{biz_sys_id}的鉴权类型: {auth_type_int}"
                )
            except (ValueError, TypeError):
                self.logger.warning(f"无法将authType转换为整数: {auth_type}")

        return auth_type_int, auth_data


class BusinessTokenService:
    """业务系统Token服务"""

    def __init__(self):
        self.logger = get_logger("BusinessTokenService")
        self.retry_executor = ApiRetryExecutor()

    async def get_business_system_token(
        self, auth_data: Dict[str, Any]
    ) -> Dict[str, Any]:
        """
        获取业务系统Token

        Args:
            auth_data: 认证数据字典

        Returns:
            包含token信息的字典
        """
        try:
            # 验证输入参数
            validation_result = self._validate_auth_data(auth_data)
            if not validation_result["valid"]:
                return {"success": False, "msg": validation_result["error"]}

            # 解析配置
            config_result = self._parse_auth_config(auth_data)
            if not config_result["valid"]:
                return {"success": False, "msg": config_result["error"]}

            # 执行API调用获取Token
            token_result = await self._execute_token_api(
                config_result["api_def"], config_result["user_params"], auth_data
            )

            return token_result

        except Exception as e:
            self.logger.error(f"获取业务系统Token失败: {str(e)}")
            return {"success": False, "msg": f"系统错误: {str(e)}"}

    def _validate_auth_data(self, auth_data: Dict[str, Any]) -> Dict[str, Any]:
        """验证认证数据"""
        if not isinstance(auth_data, dict):
            error_msg = f"auth_data类型错误: {type(auth_data)}"
            self.logger.error(error_msg)
            return {"valid": False, "error": "认证数据格式错误"}

        # 验证必要字段
        if "name" not in auth_data:
            self.logger.error("auth_data中缺少name字段")
            return {"valid": False, "error": "缺少name配置"}

        if not auth_data.get("apiVO"):
            self.logger.error("缺少apiVO信息")
            return {"valid": False, "error": "缺少API配置信息"}

        apiVO = auth_data["apiVO"]
        if not isinstance(apiVO, dict):
            error_msg = f"apiVO类型错误: {type(apiVO)}"
            self.logger.error(error_msg)
            return {"valid": False, "error": "API配置格式错误"}

        # 检查必要字段
        required_fields = ["accountConfig", "tokenPath"]
        missing_fields = [field for field in required_fields if field not in apiVO]
        if missing_fields:
            self.logger.error(f"缺少必要字段: {missing_fields}")
            return {"valid": False, "error": f"缺少必要配置字段: {missing_fields}"}

        return {"valid": True}

    def _parse_auth_config(self, auth_data: Dict[str, Any]) -> Dict[str, Any]:
        """解析认证配置"""
        try:
            apiVO = auth_data["apiVO"]

            # 解析accountConfig
            account_config = apiVO["accountConfig"]
            if isinstance(account_config, str):
                try:
                    account_config = json.loads(account_config)
                    self.logger.info("成功解析accountConfig JSON")
                except json.JSONDecodeError as e:
                    self.logger.error(f"accountConfig JSON解析失败: {str(e)}")
                    return {"valid": False, "error": "配置数据格式错误"}

            if not isinstance(account_config, dict):
                error_msg = f"accountConfig类型错误: {type(account_config)}"
                self.logger.error(error_msg)
                return {"valid": False, "error": "配置数据格式错误"}

            # 验证API定义
            api_def = apiVO.get("tcapabilityApiVO")
            if api_def is None:
                self.logger.error("缺少API配置信息")
                return {"valid": False, "error": "缺少API配置信息"}

            # 准备用户参数
            try:
                parameters_body = account_config.get("parametersBody", [])
                user_params = ParameterExtractor.extract_param_defaults(
                    parameters_body
                )
            except Exception as e:
                self.logger.error(f"准备API参数失败: {str(e)}")
                return {"valid": False, "error": "参数准备失败"}

            # 准备API定义映射
            api_def_map = {**api_def, "parameters": api_def.get("apiParameterList", [])}

            return {
                "valid": True,
                "api_def": api_def_map,
                "user_params": user_params,
                "account_config": account_config,
            }

        except Exception as e:
            self.logger.error(f"解析认证配置失败: {str(e)}")
            return {"valid": False, "error": "配置解析失败"}

    async def _execute_token_api(
        self,
        api_def: Dict[str, Any],
        user_params: Dict[str, Any],
        auth_data: Dict[str, Any],
    ) -> Dict[str, Any]:
        """执行Token获取API"""
        try:
            # 执行API调用
            api_res = await self.retry_executor.execute_with_retry(
                api_def, user_params, need_auth=False
            )

            if not api_res:
                return {"success": False, "msg": "API调用失败"}

            # 提取Token
            return self._extract_token_from_response(api_res, auth_data)

        except AuthError as e:
            self.logger.error(f"API调用失败: {str(e)}")
            return {"success": False, "msg": f"API调用失败: {str(e)}"}
        except Exception as e:
            self.logger.error(f"执行Token API异常: {str(e)}")
            return {"success": False, "msg": f"API调用异常: {str(e)}"}

    def _extract_token_from_response(
        self, api_res: Dict[str, Any], auth_data: Dict[str, Any]
    ) -> Dict[str, Any]:
        """从API响应中提取Token"""
        try:
            name = auth_data["name"]
            token_path = auth_data["apiVO"]["tokenPath"]

            value = get_nested_value({"res": api_res}, token_path)

            if not value:
                self.logger.error("未获取到有效token")
                return {"success": False, "msg": "获取token失败"}

            return {
                "tokenHeader": {name: value},
                "token": value,
                "msg": api_res.get("msg", "获取token成功"),
                "success": True,
            }

        except Exception as e:
            self.logger.error(f"处理token结果失败: {str(e)}")
            return {"success": False, "msg": "处理token结果失败"}


class AuthService:
    """认证服务，负责处理鉴权相关逻辑"""

    def __init__(self):
        self.logger = get_logger("AuthService")
        self.token_manager = TokenManager()
        self.company_auth_client = CompanyAuthClient()
        self.business_token_service = BusinessTokenService()

    async def authorize_request(
        self,
        user_id: Optional[str],
        biz_sys_id: Optional[str],
        persist_token: bool = False,
    ) -> Dict[str, Any]:
        """
        完整的请求鉴权处理

        Args:
            user_id: 用户ID
            biz_sys_id: 业务系统ID
            persist_token: 是否持久化token，默认True

        Returns:
            认证结果
        """
        self.logger.info(f"开始认证处理 - 用户ID: {user_id}, 业务系统ID: {biz_sys_id}, 持久化: {persist_token}")

        # 获取并验证token
        token_header = await self.check_user_token(user_id, biz_sys_id, persist_token=persist_token)
        self.logger.info(f"获取到Token头: {token_header}")

        if not token_header:
            return {
                "success": False,
                "error_response": {
                    "error": "获取鉴权令牌失败，请前往管理平台进行鉴权或提供临时令牌"
                },
            }

        return {
            "success": True,
            "tokenHeader": token_header,
            "source": "auth_service",  # 标记token来源
        }

    async def check_user_token(
        self,
        user_id: Optional[str],
        biz_sys_id: Optional[str],
        token: Optional[str] = None,
        persist_token: bool = False,
    ) -> Optional[Union[str, Dict[str, Any]]]:
        """
        检查用户Token是否有效，如无效则重新获取

        Args:
            user_id: 用户ID
            biz_sys_id: 业务系统ID
            token: 可选的临时Token
            persist_token: 是否持久化token

        Returns:
            Token值或None
        """
        if not user_id or not biz_sys_id:
            self.logger.warning("用户ID或业务系统ID为空，无法检查Token")
            return None

        # 生成Token名
        token_name = self.token_manager.generate_token_name(user_id, biz_sys_id)

        self.logger.info(f"Token名: {token_name}")
        
        # 如果不需要持久化，直接重新获取Token
        if not persist_token:
            self.logger.info("不使用持久化，直接获取新Token")
            return await self._refresh_user_token(user_id, biz_sys_id, token_name, persist_token)
        
        # 检查环境变量是否存在现有Token
        exists, token_value = self.token_manager.check_token_exists(token_name)
        self.logger.info(f"Token存在性检查: {exists}, 值: {token_value}")

        # 如果环境变量存在，直接返回值
        if exists:
            self.logger.info(
                f"从环境变量获取到用户{user_id}业务系统{biz_sys_id}的Token: {token_value}"
            )
            return token_value

        # 如果提供了token参数，直接使用并存储
        if token:
            if persist_token:
                self.token_manager.store_token(token_name, token)
            return token

        # 重新获取Token
        return await self._refresh_user_token(user_id, biz_sys_id, token_name, persist_token)

    async def _refresh_user_token(
        self, user_id: str, biz_sys_id: str, token_name: str, persist_token: bool = False
    ) -> Optional[Union[str, Dict[str, Any]]]:
        """刷新用户Token"""
        # 获取鉴权类型和认证数据
        auth_type, auth_data = await self.company_auth_client.get_auth_info(
            user_id, biz_sys_id
        )

        if auth_type is None:
            self.logger.error(f"无法获取用户{user_id}业务系统{biz_sys_id}的鉴权类型")
            return None

        # 根据鉴权类型获取Token
        token_value = await self._get_token_by_auth_type(
            user_id, biz_sys_id, auth_type, auth_data
        )

        self.logger.info(f"Token值: {token_value}")

        # 存储Token（根据persist_token参数决定是否持久化）
        if token_value:
            if persist_token:
                success = self.token_manager.store_token(token_name, token_value)
                if not success:
                    self.logger.error(f"存储用户{user_id}业务系统{biz_sys_id}的Token失败")
                else:
                    self.logger.info(f"成功存储用户{user_id}业务系统{biz_sys_id}的Token到环境变量: {token_name}")
            else:
                self.logger.info(f"跳过持久化，用户{user_id}业务系统{biz_sys_id}的Token仅在内存中使用")
        else:
            self.logger.warning(f"未能获取到用户{user_id}业务系统{biz_sys_id}的Token，token_value: {token_value}")

        return token_value

    def clear_token(self, user_id: str, biz_sys_id: str) -> bool:
        """
        清空指定用户的token

        Args:
            user_id: 用户ID
            biz_sys_id: 业务系统ID

        Returns:
            清空是否成功
        """
        if not user_id or not biz_sys_id:
            self.logger.warning("用户ID或业务系统ID为空，无法清空Token")
            return False

        # 生成Token名
        token_name = self.token_manager.generate_token_name(user_id, biz_sys_id)
        
        # 删除环境变量中的token
        success = EnvironmentManager.delete(token_name)
        
        if success:
            self.logger.info(f"成功清空用户{user_id}业务系统{biz_sys_id}的Token: {token_name}")
        else:
            self.logger.error(f"清空用户{user_id}业务系统{biz_sys_id}的Token失败: {token_name}")
            
        return success

    def clear_all_tokens(self) -> bool:
        """
        清空所有持久化的token

        Returns:
            清空是否成功
        """
        try:
            # 加载所有token
            persistent_tokens = EnvironmentManager._load_persistent_tokens()
            
            # 删除所有token类型的环境变量
            for token_name in list(persistent_tokens.keys()):
                if token_name.endswith('token'):
                    EnvironmentManager.delete(token_name)
            
            self.logger.info("成功清空所有持久化token")
            return True
        except Exception as e:
            self.logger.error(f"清空所有token失败: {e}")
            return False

    async def _get_token_by_auth_type(
        self, user_id: str, biz_sys_id: str, auth_type: int, auth_data: Dict[str, Any]
    ) -> Optional[Dict[str, Any]]:
        """根据鉴权类型获取Token"""
        try:
            if auth_type == 0:
                # 直接使用apiKey作为Token
                return self._get_api_key_token(user_id, biz_sys_id, auth_data)
            elif auth_type == 1:
                # 调用登录接口获取Token
                return await self._get_login_token(user_id, biz_sys_id, auth_data)
            else:
                self.logger.warning(f"不支持的鉴权类型: {auth_type}")
                return None
        except Exception as e:
            self.logger.error(f"获取Token失败: {str(e)}")
            return None

    def _get_api_key_token(
        self, user_id: str, biz_sys_id: str, auth_data: Dict[str, Any]
    ) -> Optional[Dict[str, Any]]:
        """获取API Key类型的Token"""
        api_key = auth_data.get("apiKey")
        name = auth_data.get("name")

        if api_key and name:
            self.logger.info(f"使用apiKey作为用户{user_id}业务系统{biz_sys_id}的Token")
            return {name: api_key}
        else:
            self.logger.warning(f"用户{user_id}业务系统{biz_sys_id}的apiKey或name为空")
            return None

    async def _get_login_token(
        self, user_id: str, biz_sys_id: str, auth_data: Dict[str, Any]
    ) -> Optional[Dict[str, Any]]:
        """获取登录类型的Token"""
        self.logger.info(f"通过登录接口获取用户{user_id}业务系统{biz_sys_id}的Token")

        login_res = await self.business_token_service.get_business_system_token(
            auth_data
        )

        if login_res and login_res.get("tokenHeader") is not None:
            return login_res.get("tokenHeader")
        else:
            error_msg = login_res.get("msg", "未知错误") if login_res else "未知错误"
            self.logger.error(f"获取Token失败: {error_msg}")
            return None


# 兼容性函数 - 保持向后兼容
def extract_param_defaults(param_list: list) -> Dict[str, Any]:
    """提取参数默认值（兼容性函数）"""
    return ParameterExtractor.extract_param_defaults(param_list)


async def execute_api_call_with_retry(
    api_config: Dict[str, Any],
    user_params: Dict[str, Any],
    need_auth: bool = False,
    max_attempts: int = 3,
    base_delay: int = 1,
    max_delay: int = 60,
) -> Optional[Dict[str, Any]]:
    """API重试调用（兼容性函数）"""
    executor = ApiRetryExecutor(max_attempts, base_delay, max_delay)
    return await executor.execute_with_retry(api_config, user_params, need_auth)


class EnvManager:
    """环境变量管理器（兼容性类）"""

    @staticmethod
    def get_env(key: str, default: Optional[str] = None) -> Optional[str]:
        return EnvironmentManager.get(key, default)

    @staticmethod
    def set_env(key: str, value: str) -> bool:
        return EnvironmentManager.set(key, value)

    @staticmethod
    def exists_env(key: str) -> bool:
        return EnvironmentManager.exists(key)


class Config:
    """配置类（兼容性）"""
    pass


async def test_auth_service():
    """测试认证服务"""
    auth_service = AuthService()
    token_header = await auth_service.check_user_token(
        "1932715213891215361", "1932385006853664770"
    )
    logger.info(f"测试结果 - Token头: {token_header}")


if __name__ == "__main__":
    # 配置日志
    from ..util.logger_config import setup_logging
    import logging
    setup_logging(log_level=logging.INFO)

    asyncio.run(test_auth_service())
