"""
配置模块 - 管理MCP服务器配置
"""
import os
from typing import Dict, Any, Optional
import json

class Settings:
    """配置管理类"""
    
    def __init__(self, config_file: Optional[str] = None):
        """
        初始化配置
        
        Args:
            config_file: 配置文件路径，如果为None则使用环境变量和默认值
        """
        # 默认配置
        self.config = {
            # MCP服务配置
            "MCP_NAME": "mytools",
            "MCP_TRANSPORT": "stdio",  # stdio, http, sse
            "MCP_HTTP_HOST": "127.0.0.1",
            "MCP_HTTP_PORT": 5678,
            "MCP_SSE_PORT": 8000,
            
            # 日志配置
            "LOG_LEVEL": "DEBUG",
            "LOG_FILE": "logs/mcp_server.log",
            
            # API密钥配置
            "WEATHER_API_KEY": "",
            "TRANSLATION_API_KEY": "",
            
            # 服务URLs
            "WEATHER_API_URL": "https://api.example.com/weather",
            "TRANSLATION_API_URL": "https://api.example.com/translate",
            
            # 业务API配置
            # "BUSINESS_API_BASE_URL": "http://10.110.11.135:8897",
            "BUSINESS_API_BASE_URL": "http://172.31.236.244:8397",
            "BUSINESS_API_VERSION": "v1",
            "BUSINESS_API_ACCESS_TOKEN": "",
            "BUSINESS_API_TIMEOUT": 30.0,
        }
        
        # 从配置文件加载
        if config_file and os.path.exists(config_file):
            self._load_from_file(config_file)
        
        # 从环境变量更新配置
        self._load_from_env()
    
    def _load_from_file(self, config_file: str) -> None:
        """从配置文件加载设置"""
        try:
            with open(config_file, 'r', encoding='utf-8') as f:
                file_config = json.load(f)
                self.config.update(file_config)
        except Exception as e:
            print(f"警告: 无法加载配置文件 {config_file}: {str(e)}")
    
    def _load_from_env(self) -> None:
        """从环境变量加载设置"""
        for key in self.config:
            env_value = os.environ.get(key)
            if env_value is not None:
                # 尝试将数字和布尔值字符串转换为对应类型
                if env_value.isdigit():
                    env_value = int(env_value)
                elif env_value.lower() in ('true', 'false'):
                    env_value = env_value.lower() == 'true'
                
                self.config[key] = env_value
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        return self.config.get(key, default)
    
    def set(self, key: str, value: Any) -> None:
        """设置配置值"""
        self.config[key] = value
    
    def __getitem__(self, key: str) -> Any:
        """支持字典方式访问配置"""
        return self.config.get(key)
    
    def __setitem__(self, key: str, value: Any) -> None:
        """支持字典方式更新配置"""
        self.config[key] = value
    
    def as_dict(self) -> Dict[str, Any]:
        """返回配置的字典表示"""
        return self.config.copy()

# 创建全局设置实例
settings = Settings() 