"""
TradingAgents AkShare配置模块

该模块提供AkShare数据源的配置管理，包括：
- 数据源配置参数
- 缓存策略设置
- 成本跟踪和优化
- 环境变量管理

@author TradingAgents团队
@version MVP-2.0 (AkShare集成版)
@since 2024-12
"""

import os
from typing import Dict, Any, Optional, List
from dataclasses import dataclass, field
from datetime import datetime
import logging

logger = logging.getLogger(__name__)


@dataclass
class AkShareDataConfig:
    """
    AkShare数据配置类
    
    @description 管理AkShare数据源的所有配置参数
    """
    
    # 基础配置
    enable_akshare: bool = True
    user_agent: str = "TradingAgents-AkShare/2.0"
    max_retries: int = 3
    retry_delay: float = 1.0
    request_timeout: int = 30
    
    # 缓存配置
    cache_enabled: bool = True
    cache_ttl_hours: int = 6
    cache_db_path: str = "data/cache/akshare_cache.db"
    max_cache_size_mb: int = 500
    
    # 数据更新频率 (分钟)
    realtime_update_interval: int = 5
    history_update_interval: int = 360  # 6小时
    news_update_interval: int = 30
    
    # 支持的市场
    supported_markets: List[str] = field(default_factory=lambda: [
        "a_stock",      # A股
        "hk_stock",     # 港股
        "us_stock",     # 美股
        "futures",      # 期货
        "indices",      # 指数
        "fund_flow",    # 资金流向
        "macro"         # 宏观数据
    ])
    
    # 数据质量控制
    enable_data_validation: bool = True
    min_data_points: int = 10
    max_missing_ratio: float = 0.1
    
    # 成本跟踪
    monthly_cost: float = 0.0  # AkShare完全免费
    cost_currency: str = "USD"
    
    # 备用数据源配置
    enable_fallback: bool = True
    fallback_sources: List[str] = field(default_factory=lambda: [
        "yahoo_finance",
        "cached_data"
    ])


@dataclass
class AkShareMarketConfig:
    """
    AkShare市场特定配置
    
    @description 针对不同市场的特殊配置
    """
    
    # A股配置
    a_stock_config: Dict[str, Any] = field(default_factory=lambda: {
        "enable_realtime": True,
        "enable_history": True,
        "enable_fund_flow": True,
        "enable_technical": True,
        "default_adjust": "qfq",  # 前复权
        "cache_ttl_minutes": 5,
        "supported_periods": ["1d", "1w", "1m", "3m", "6m", "1y", "2y"]
    })
    
    # 港股配置
    hk_stock_config: Dict[str, Any] = field(default_factory=lambda: {
        "enable_realtime": True,
        "enable_history": True,
        "enable_fund_flow": False,
        "cache_ttl_minutes": 5,
        "currency": "HKD",
        "supported_periods": ["1d", "1w", "1m", "3m", "6m", "1y", "2y"]
    })
    
    # 美股配置
    us_stock_config: Dict[str, Any] = field(default_factory=lambda: {
        "enable_realtime": True,
        "enable_history": True,
        "enable_fund_flow": False,
        "cache_ttl_minutes": 5,
        "currency": "USD",
        "supported_periods": ["1d", "1w", "1m", "3m", "6m", "1y", "2y"]
    })
    
    # 期货配置
    futures_config: Dict[str, Any] = field(default_factory=lambda: {
        "enable_domestic": True,
        "enable_foreign": True,
        "enable_options": True,
        "cache_ttl_minutes": 5,
        "supported_exchanges": ["SHFE", "DCE", "CZCE", "CFFEX", "INE", "GFEX"]
    })
    
    # 指数配置
    indices_config: Dict[str, Any] = field(default_factory=lambda: {
        "enable_major_indices": True,
        "enable_sector_indices": True,
        "enable_custom_indices": True,
        "cache_ttl_minutes": 5,
        "default_indices": ["000001", "000300", "399001", "399006"]
    })


@dataclass
class AkSharePerformanceConfig:
    """
    AkShare性能配置
    
    @description 性能优化相关配置
    """
    
    # 并发配置
    max_concurrent_requests: int = 5
    request_pool_size: int = 10
    
    # 批量处理配置
    batch_size: int = 50
    batch_timeout: int = 60
    
    # 内存管理
    max_memory_usage_mb: int = 1024
    gc_threshold: int = 100
    
    # 网络配置
    connection_timeout: int = 10
    read_timeout: int = 30
    max_redirects: int = 3
    
    # 错误处理
    max_error_rate: float = 0.1
    error_cooldown_minutes: int = 5
    
    # 监控配置
    enable_performance_monitoring: bool = True
    log_slow_requests: bool = True
    slow_request_threshold: float = 5.0


class AkShareConfigManager:
    """
    AkShare配置管理器
    
    @description 统一管理所有AkShare相关配置
    """
    
    def __init__(self, config_file: Optional[str] = None):
        """
        初始化配置管理器
        
        @param {Optional[str]} config_file - 配置文件路径
        """
        self.config_file = config_file
        self.data_config = AkShareDataConfig()
        self.market_config = AkShareMarketConfig()
        self.performance_config = AkSharePerformanceConfig()
        
        # 从环境变量加载配置
        self._load_from_env()
        
        # 从配置文件加载配置
        if config_file and os.path.exists(config_file):
            self._load_from_file(config_file)
        
        logger.info("AkShare配置管理器初始化完成")
    
    def _load_from_env(self):
        """从环境变量加载配置"""
        try:
            # 基础配置
            if os.getenv("AKSHARE_CACHE_TTL_HOURS"):
                self.data_config.cache_ttl_hours = int(os.getenv("AKSHARE_CACHE_TTL_HOURS"))
            
            if os.getenv("AKSHARE_MAX_RETRIES"):
                self.data_config.max_retries = int(os.getenv("AKSHARE_MAX_RETRIES"))
            
            if os.getenv("AKSHARE_CACHE_PATH"):
                self.data_config.cache_db_path = os.getenv("AKSHARE_CACHE_PATH")
            
            # 性能配置
            if os.getenv("AKSHARE_MAX_CONCURRENT"):
                self.performance_config.max_concurrent_requests = int(os.getenv("AKSHARE_MAX_CONCURRENT"))
            
            if os.getenv("AKSHARE_BATCH_SIZE"):
                self.performance_config.batch_size = int(os.getenv("AKSHARE_BATCH_SIZE"))
            
            logger.info("环境变量配置加载完成")
            
        except Exception as e:
            logger.error(f"加载环境变量配置失败: {e}")
    
    def _load_from_file(self, config_file: str):
        """从配置文件加载配置"""
        try:
            import json
            with open(config_file, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
            
            # 更新配置
            if "data_config" in config_data:
                for key, value in config_data["data_config"].items():
                    if hasattr(self.data_config, key):
                        setattr(self.data_config, key, value)
            
            if "market_config" in config_data:
                for key, value in config_data["market_config"].items():
                    if hasattr(self.market_config, key):
                        setattr(self.market_config, key, value)
            
            if "performance_config" in config_data:
                for key, value in config_data["performance_config"].items():
                    if hasattr(self.performance_config, key):
                        setattr(self.performance_config, key, value)
            
            logger.info(f"配置文件加载完成: {config_file}")
            
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}")
    
    def get_market_config(self, market: str) -> Dict[str, Any]:
        """
        获取特定市场的配置
        
        @param {str} market - 市场类型
        @returns {Dict[str, Any]} 市场配置
        """
        config_map = {
            "a_stock": self.market_config.a_stock_config,
            "hk_stock": self.market_config.hk_stock_config,
            "us_stock": self.market_config.us_stock_config,
            "futures": self.market_config.futures_config,
            "indices": self.market_config.indices_config
        }
        
        return config_map.get(market, {})
    
    def validate_config(self) -> Dict[str, Any]:
        """
        验证配置有效性
        
        @returns {Dict[str, Any]} 验证结果
        """
        validation_result = {
            "valid": True,
            "errors": [],
            "warnings": []
        }
        
        try:
            # 验证缓存配置
            if self.data_config.cache_ttl_hours <= 0:
                validation_result["errors"].append("缓存TTL必须大于0")
            
            if self.data_config.max_retries < 0:
                validation_result["errors"].append("最大重试次数不能为负数")
            
            # 验证性能配置
            if self.performance_config.max_concurrent_requests <= 0:
                validation_result["errors"].append("最大并发请求数必须大于0")
            
            if self.performance_config.batch_size <= 0:
                validation_result["errors"].append("批量大小必须大于0")
            
            # 验证缓存目录
            cache_dir = os.path.dirname(self.data_config.cache_db_path)
            if not os.path.exists(cache_dir):
                try:
                    os.makedirs(cache_dir, exist_ok=True)
                    validation_result["warnings"].append(f"创建缓存目录: {cache_dir}")
                except Exception as e:
                    validation_result["errors"].append(f"无法创建缓存目录: {e}")
            
            # 设置验证结果
            validation_result["valid"] = len(validation_result["errors"]) == 0
            
        except Exception as e:
            validation_result["valid"] = False
            validation_result["errors"].append(f"配置验证异常: {e}")
        
        return validation_result
    
    def get_cost_summary(self) -> Dict[str, Any]:
        """
        获取成本摘要
        
        @returns {Dict[str, Any]} 成本摘要
        """
        return {
            "akshare": {
                "monthly_cost": self.data_config.monthly_cost,
                "currency": self.data_config.cost_currency,
                "description": "完全免费"
            },
            "savings_vs_finnhub": {
                "monthly_savings": 197.0,
                "annual_savings": 2364.0,
                "percentage_savings": 100.0
            },
            "data_coverage": {
                "markets": len(self.data_config.supported_markets),
                "features": [
                    "实时行情", "历史数据", "资金流向", 
                    "技术指标", "期货数据", "宏观数据"
                ]
            },
            "performance": {
                "api_limits": "无限制",
                "data_freshness": f"{self.data_config.realtime_update_interval}分钟",
                "cache_efficiency": f"{self.data_config.cache_ttl_hours}小时缓存"
            }
        }
    
    def export_config(self, output_file: str) -> bool:
        """
        导出配置到文件
        
        @param {str} output_file - 输出文件路径
        @returns {bool} 是否导出成功
        """
        try:
            import json
            from dataclasses import asdict
            
            config_data = {
                "data_config": asdict(self.data_config),
                "market_config": asdict(self.market_config),
                "performance_config": asdict(self.performance_config),
                "export_timestamp": datetime.now().isoformat(),
                "version": "2.0"
            }
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, indent=2, ensure_ascii=False)
            
            logger.info(f"配置导出成功: {output_file}")
            return True
            
        except Exception as e:
            logger.error(f"配置导出失败: {e}")
            return False


# 全局配置实例
_config_manager = None

def get_akshare_config() -> AkShareConfigManager:
    """
    获取全局AkShare配置管理器实例
    
    @returns {AkShareConfigManager} 配置管理器实例
    """
    global _config_manager
    if _config_manager is None:
        _config_manager = AkShareConfigManager()
    return _config_manager


def init_akshare_config(config_file: Optional[str] = None) -> AkShareConfigManager:
    """
    初始化AkShare配置
    
    @param {Optional[str]} config_file - 配置文件路径
    @returns {AkShareConfigManager} 配置管理器实例
    """
    global _config_manager
    _config_manager = AkShareConfigManager(config_file)
    return _config_manager


if __name__ == "__main__":
    # 测试配置管理器
    print("=== AkShare配置管理器测试 ===")
    
    # 初始化配置
    config_manager = init_akshare_config()
    
    # 验证配置
    validation = config_manager.validate_config()
    print(f"配置验证: {'✅ 通过' if validation['valid'] else '❌ 失败'}")
    
    if validation['errors']:
        print("错误:")
        for error in validation['errors']:
            print(f"  - {error}")
    
    if validation['warnings']:
        print("警告:")
        for warning in validation['warnings']:
            print(f"  - {warning}")
    
    # 成本摘要
    cost_summary = config_manager.get_cost_summary()
    print(f"\n成本摘要:")
    print(f"  月度成本: ${cost_summary['akshare']['monthly_cost']}")
    print(f"  年度节省: ${cost_summary['savings_vs_finnhub']['annual_savings']}")
    print(f"  数据覆盖: {cost_summary['data_coverage']['markets']}个市场")
    
    # 市场配置测试
    a_stock_config = config_manager.get_market_config("a_stock")
    print(f"\nA股配置: {len(a_stock_config)}项设置")
    
    print("\n=== AkShare配置管理器测试完成 ===")