#!/usr/bin/env python3
"""
TradingAgents AkShare版本安装脚本

自动化安装和配置TradingAgents AkShare集成版本：
- 安装所有必需依赖
- 配置AkShare数据源
- 创建必要的目录结构
- 验证系统功能
- 100%免费，零API成本

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

import os
import sys
import subprocess
import json
from pathlib import Path
from typing import Dict, Any, List
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class AkShareSetupManager:
    """
    AkShare版本安装管理器
    
    @description 自动化安装和配置AkShare集成版本
    """
    
    def __init__(self):
        """初始化安装管理器"""
        self.project_root = Path(__file__).parent
        self.python_executable = sys.executable
        self.setup_status = {
            "dependencies": False,
            "directories": False,
            "config": False,
            "validation": False
        }
        
        print("🚀 TradingAgents AkShare版本安装程序")
        print("💰 100%免费数据源，零API成本！")
        print("=" * 50)
    
    def run_setup(self) -> bool:
        """
        运行完整安装流程
        
        @returns {bool} 安装是否成功
        """
        try:
            print("\n📦 开始安装TradingAgents AkShare版本...")
            
            # 1. 检查Python版本
            if not self._check_python_version():
                return False
            
            # 2. 安装依赖
            if not self._install_dependencies():
                return False
            
            # 3. 创建目录结构
            if not self._create_directories():
                return False
            
            # 4. 生成配置文件
            if not self._create_config_files():
                return False
            
            # 5. 验证安装
            if not self._validate_installation():
                return False
            
            # 6. 显示安装总结
            self._show_installation_summary()
            
            return True
            
        except Exception as e:
            logger.error(f"安装失败: {e}")
            print(f"❌ 安装失败: {e}")
            return False
    
    def _check_python_version(self) -> bool:
        """检查Python版本"""
        try:
            version = sys.version_info
            print(f"🐍 检查Python版本: {version.major}.{version.minor}.{version.micro}")
            
            if version.major < 3 or (version.major == 3 and version.minor < 8):
                print("❌ 错误: 需要Python 3.8或更高版本")
                return False
            
            print("✅ Python版本检查通过")
            return True
            
        except Exception as e:
            logger.error(f"Python版本检查失败: {e}")
            return False
    
    def _install_dependencies(self) -> bool:
        """安装依赖包"""
        try:
            print("\n📚 安装依赖包...")
            
            # 升级pip
            print("⬆️ 升级pip...")
            subprocess.run([
                self.python_executable, "-m", "pip", "install", "--upgrade", "pip"
            ], check=True, capture_output=True)
            
            # 安装requirements_free.txt中的依赖
            requirements_file = self.project_root / "requirements_free.txt"
            if requirements_file.exists():
                print("📋 安装requirements_free.txt中的依赖...")
                subprocess.run([
                    self.python_executable, "-m", "pip", "install", "-r", str(requirements_file)
                ], check=True)
            else:
                # 手动安装核心依赖
                core_packages = [
                    "akshare>=1.12.0",
                    "langchain>=0.1.0", 
                    "langchain-openai>=0.0.5",
                    "pandas>=1.5.0",
                    "numpy>=1.21.0",
                    "requests>=2.28.0",
                    "pydantic>=2.0.0",
                    "python-dotenv>=0.19.0"
                ]
                
                print("📦 安装核心依赖包...")
                for package in core_packages:
                    print(f"   安装 {package}...")
                    subprocess.run([
                        self.python_executable, "-m", "pip", "install", package
                    ], check=True, capture_output=True)
            
            self.setup_status["dependencies"] = True
            print("✅ 依赖包安装完成")
            return True
            
        except subprocess.CalledProcessError as e:
            logger.error(f"依赖安装失败: {e}")
            print(f"❌ 依赖安装失败: {e}")
            return False
        except Exception as e:
            logger.error(f"依赖安装异常: {e}")
            print(f"❌ 依赖安装异常: {e}")
            return False
    
    def _create_directories(self) -> bool:
        """创建必要的目录结构"""
        try:
            print("\n📁 创建目录结构...")
            
            directories = [
                "data/cache",
                "data/exports", 
                "logs",
                "config",
                "reports",
                "temp"
            ]
            
            for directory in directories:
                dir_path = self.project_root / directory
                dir_path.mkdir(parents=True, exist_ok=True)
                print(f"   📂 创建目录: {directory}")
            
            self.setup_status["directories"] = True
            print("✅ 目录结构创建完成")
            return True
            
        except Exception as e:
            logger.error(f"目录创建失败: {e}")
            print(f"❌ 目录创建失败: {e}")
            return False
    
    def _create_config_files(self) -> bool:
        """创建配置文件"""
        try:
            print("\n⚙️ 创建配置文件...")
            
            # 创建AkShare配置文件
            akshare_config = {
                "data_config": {
                    "enable_akshare": True,
                    "cache_enabled": True,
                    "cache_ttl_hours": 6,
                    "cache_db_path": "data/cache/akshare_cache.db",
                    "realtime_update_interval": 5,
                    "supported_markets": ["a_stock", "hk_stock", "us_stock", "futures", "indices"]
                },
                "market_config": {
                    "a_stock_config": {
                        "enable_realtime": True,
                        "enable_history": True,
                        "enable_fund_flow": True,
                        "default_adjust": "qfq"
                    },
                    "us_stock_config": {
                        "enable_realtime": True,
                        "enable_history": True,
                        "currency": "USD"
                    }
                },
                "performance_config": {
                    "max_concurrent_requests": 5,
                    "batch_size": 50,
                    "enable_performance_monitoring": True
                }
            }
            
            config_file = self.project_root / "config" / "akshare_config.json"
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(akshare_config, f, indent=2, ensure_ascii=False)
            print(f"   📄 创建AkShare配置: {config_file}")
            
            # 创建环境变量模板
            env_template = """# TradingAgents AkShare版本环境变量配置
# 注意: AkShare完全免费，无需API密钥！

# OpenAI配置 (用于LLM分析)
OPENAI_API_KEY=your_openai_api_key_here

# AkShare配置 (可选)
AKSHARE_CACHE_TTL_HOURS=6
AKSHARE_MAX_RETRIES=3
AKSHARE_CACHE_PATH=data/cache/akshare_cache.db

# 系统配置
LOG_LEVEL=INFO
ENABLE_PERFORMANCE_MONITORING=true

# 成本节省信息
# FinnHub成本: $197/月
# AkShare成本: $0/月
# 节省: 100%
"""
            
            env_file = self.project_root / ".env.akshare"
            with open(env_file, 'w', encoding='utf-8') as f:
                f.write(env_template)
            print(f"   📄 创建环境变量模板: {env_file}")
            
            self.setup_status["config"] = True
            print("✅ 配置文件创建完成")
            return True
            
        except Exception as e:
            logger.error(f"配置文件创建失败: {e}")
            print(f"❌ 配置文件创建失败: {e}")
            return False
    
    def _validate_installation(self) -> bool:
        """验证安装"""
        try:
            print("\n🔍 验证安装...")
            
            # 测试AkShare导入
            print("   测试AkShare导入...")
            try:
                import akshare as ak
                print(f"   ✅ AkShare版本: {ak.__version__}")
            except ImportError as e:
                print(f"   ❌ AkShare导入失败: {e}")
                return False
            
            # 测试其他核心依赖
            core_modules = [
                ("pandas", "pd"),
                ("numpy", "np"), 
                ("requests", "requests"),
                ("langchain", "langchain"),
                ("pydantic", "pydantic")
            ]
            
            for module_name, import_name in core_modules:
                try:
                    __import__(module_name)
                    print(f"   ✅ {module_name} 导入成功")
                except ImportError as e:
                    print(f"   ❌ {module_name} 导入失败: {e}")
                    return False
            
            # 测试AkShare数据获取
            print("   测试AkShare数据获取...")
            try:
                # 获取A股指数数据 (测试用)
                test_data = ak.stock_zh_index_spot_em(symbol="沪深重要指数")
                if not test_data.empty:
                    print(f"   ✅ AkShare数据获取成功: {len(test_data)}个指数")
                else:
                    print("   ⚠️ AkShare数据为空，但连接正常")
            except Exception as e:
                print(f"   ⚠️ AkShare数据获取测试失败: {e}")
                print("   💡 这可能是网络问题，不影响安装")
            
            self.setup_status["validation"] = True
            print("✅ 安装验证完成")
            return True
            
        except Exception as e:
            logger.error(f"安装验证失败: {e}")
            print(f"❌ 安装验证失败: {e}")
            return False
    
    def _show_installation_summary(self):
        """显示安装总结"""
        print("\n" + "=" * 60)
        print("🎉 TradingAgents AkShare版本安装完成！")
        print("=" * 60)
        
        print("\n📊 安装状态:")
        for component, status in self.setup_status.items():
            status_icon = "✅" if status else "❌"
            print(f"   {status_icon} {component}")
        
        print("\n💰 成本对比:")
        print("   📈 FinnHub版本: $197/月")
        print("   🆓 AkShare版本: $0/月")
        print("   💸 节省: $197/月 (100%)")
        
        print("\n🚀 快速开始:")
        print("   1. 配置OpenAI API密钥 (编辑 .env.akshare)")
        print("   2. 运行市场分析:")
        print("      python main_akshare.py --action overview")
        print("   3. 分析个股:")
        print("      python main_akshare.py --action stock --symbol 000001")
        print("   4. 搜索股票:")
        print("      python main_akshare.py --action search --query 平安")
        
        print("\n📚 支持的功能:")
        features = [
            "实时行情数据 (A股/港股/美股)",
            "历史K线数据",
            "资金流向分析", 
            "技术指标计算",
            "板块轮动分析",
            "市场广度分析",
            "期货数据",
            "智能投资建议"
        ]
        for feature in features:
            print(f"   ✨ {feature}")
        
        print("\n🔗 相关文件:")
        print(f"   📄 主程序: main_akshare.py")
        print(f"   ⚙️ 配置: config/akshare_config.json")
        print(f"   🌍 环境变量: .env.akshare")
        print(f"   📋 依赖: requirements_free.txt")
        
        print("\n💡 提示:")
        print("   • AkShare完全免费，无需任何API密钥")
        print("   • 数据覆盖全面，质量可靠")
        print("   • 支持多市场分析")
        print("   • 智能缓存，提升性能")
        
        print("\n🆘 如需帮助:")
        print("   • 查看文档: docs/")
        print("   • 检查日志: logs/")
        print("   • 运行测试: python -m pytest tests/")


def main():
    """主函数"""
    try:
        setup_manager = AkShareSetupManager()
        success = setup_manager.run_setup()
        
        if success:
            print("\n🎊 安装成功完成！")
            print("现在您可以使用100%免费的TradingAgents AkShare版本了！")
            sys.exit(0)
        else:
            print("\n💥 安装失败！")
            print("请检查错误信息并重试。")
            sys.exit(1)
            
    except KeyboardInterrupt:
        print("\n⏹️ 用户中断安装")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ 安装程序异常: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()