#!/usr/bin/env python3
"""
TradingAgents MVP免费版本快速设置脚本

该脚本帮助用户快速设置和配置TradingAgents免费版本，包括：
- 环境检查
- 依赖安装
- 配置文件生成
- API密钥设置
- 系统测试

@author TradingAgents团队
@version MVP-1.0
@since 2024-12
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path
from typing import Dict, Any, Optional
import json


class TradingAgentsSetup:
    """TradingAgents免费版本设置助手"""
    
    def __init__(self):
        self.project_root = Path(__file__).parent
        self.python_version = sys.version_info
        self.setup_log = []
    
    def log(self, message: str, level: str = "INFO"):
        """记录设置日志"""
        log_entry = f"[{level}] {message}"
        self.setup_log.append(log_entry)
        print(log_entry)
    
    def check_python_version(self) -> bool:
        """检查Python版本"""
        self.log("检查Python版本...")
        
        if self.python_version < (3, 8):
            self.log(f"❌ Python版本过低: {self.python_version.major}.{self.python_version.minor}", "ERROR")
            self.log("   TradingAgents需要Python 3.8或更高版本", "ERROR")
            return False
        
        self.log(f"✅ Python版本: {self.python_version.major}.{self.python_version.minor}.{self.python_version.micro}")
        return True
    
    def check_required_commands(self) -> bool:
        """检查必需的命令"""
        self.log("检查必需的系统命令...")
        
        required_commands = ["pip", "git"]
        missing_commands = []
        
        for cmd in required_commands:
            if not shutil.which(cmd):
                missing_commands.append(cmd)
        
        if missing_commands:
            self.log(f"❌ 缺少必需命令: {', '.join(missing_commands)}", "ERROR")
            return False
        
        self.log("✅ 所有必需命令都可用")
        return True
    
    def create_directories(self):
        """创建必需的目录"""
        self.log("创建项目目录结构...")
        
        directories = [
            "data/cache",
            "logs",
            "config",
            "tradingagents/config",
            "tradingagents/dataflows",
            "tradingagents/agents/analysts"
        ]
        
        for directory in directories:
            dir_path = self.project_root / directory
            dir_path.mkdir(parents=True, exist_ok=True)
            self.log(f"   创建目录: {directory}")
        
        self.log("✅ 目录结构创建完成")
    
    def install_dependencies(self) -> bool:
        """安装Python依赖"""
        self.log("安装Python依赖...")
        
        requirements_file = self.project_root / "requirements_free.txt"
        
        if not requirements_file.exists():
            self.log("❌ requirements_free.txt文件不存在", "ERROR")
            return False
        
        try:
            # 升级pip
            subprocess.run([
                sys.executable, "-m", "pip", "install", "--upgrade", "pip"
            ], check=True, capture_output=True)
            
            # 安装依赖
            subprocess.run([
                sys.executable, "-m", "pip", "install", "-r", str(requirements_file)
            ], check=True, capture_output=True)
            
            self.log("✅ 依赖安装完成")
            return True
            
        except subprocess.CalledProcessError as e:
            self.log(f"❌ 依赖安装失败: {e}", "ERROR")
            return False
    
    def setup_environment_file(self):
        """设置环境变量文件"""
        self.log("设置环境变量文件...")
        
        env_template = self.project_root / "env.template"
        env_file = self.project_root / ".env"
        
        if env_file.exists():
            self.log("   .env文件已存在，跳过创建")
            return
        
        if env_template.exists():
            shutil.copy(env_template, env_file)
            self.log("✅ 已从模板创建.env文件")
            self.log("   请编辑.env文件并填入您的API密钥", "WARNING")
        else:
            # 创建基础的.env文件
            basic_env = """# TradingAgents MVP免费版本环境变量
# 必需的API密钥
OPENAI_API_KEY=your_openai_api_key_here

# 可选的API密钥
ALPHA_VANTAGE_API_KEY=your_alpha_vantage_api_key_here
REDDIT_CLIENT_ID=your_reddit_client_id_here
REDDIT_CLIENT_SECRET=your_reddit_client_secret_here

# 系统配置
TRADING_LOG_LEVEL=INFO
TRADING_DEBUG_MODE=false
TRADING_WEB_PORT=8501
TRADING_RISK_TOLERANCE=moderate
"""
            
            with open(env_file, 'w', encoding='utf-8') as f:
                f.write(basic_env)
            
            self.log("✅ 已创建基础.env文件")
            self.log("   请编辑.env文件并填入您的API密钥", "WARNING")
    
    def create_config_files(self):
        """创建配置文件"""
        self.log("创建配置文件...")
        
        # 创建基础配置
        config_dir = self.project_root / "config"
        
        # 数据源配置
        data_sources_config = {
            "alpha_vantage_max_calls_per_day": 400,
            "alpha_vantage_calls_per_minute": 5,
            "sec_edgar_user_agent": "TradingAgents-MVP/1.0 (contact@tradingagents.ai)",
            "sec_edgar_rate_limit": 10.0,
            "yahoo_finance_timeout": 30,
            "yahoo_finance_retry_count": 3,
            "cache_enabled": True,
            "cache_directory": "data/cache",
            "cache_ttl_hours": 6,
            "cache_max_size_mb": 500,
            "news_sources_enabled": ["yahoo_finance", "google_news"],
            "news_max_articles_per_source": 10,
            "enable_fallback_sources": True,
            "max_retry_attempts": 3,
            "request_timeout": 30,
            "log_level": "INFO",
            "enable_performance_monitoring": True,
            "enable_cost_tracking": True
        }
        
        with open(config_dir / "data_sources_config.json", 'w', encoding='utf-8') as f:
            json.dump(data_sources_config, f, indent=2, ensure_ascii=False)
        
        # 主配置
        main_config = {
            "openai_model": "gpt-4",
            "openai_temperature": 0.1,
            "openai_max_tokens": 2000,
            "reddit_user_agent": "TradingAgents-MVP/1.0",
            "max_analysis_depth": 3,
            "confidence_threshold": 0.7,
            "risk_tolerance": "moderate",
            "debug_mode": False,
            "enable_web_interface": True,
            "web_port": 8501,
            "max_concurrent_requests": 5,
            "request_pool_size": 10
        }
        
        with open(config_dir / "trading_config.json", 'w', encoding='utf-8') as f:
            json.dump(main_config, f, indent=2, ensure_ascii=False)
        
        self.log("✅ 配置文件创建完成")
    
    def test_system(self) -> bool:
        """测试系统功能"""
        self.log("测试系统功能...")
        
        try:
            # 测试导入
            sys.path.insert(0, str(self.project_root))
            
            # 测试配置模块
            from tradingagents.config.free_config import get_config
            config = get_config()
            self.log("   ✅ 配置模块测试通过")
            
            # 测试数据源模块
            from tradingagents.dataflows.free_alternatives import DataSourceConfig
            data_config = DataSourceConfig()
            self.log("   ✅ 数据源模块测试通过")
            
            # 测试基本面分析师模块
            from tradingagents.agents.analysts.fundamentals_analyst_free import FreeFundamentalsAnalyst
            self.log("   ✅ 基本面分析师模块测试通过")
            
            self.log("✅ 系统功能测试完成")
            return True
            
        except Exception as e:
            self.log(f"❌ 系统测试失败: {e}", "ERROR")
            return False
    
    def print_next_steps(self):
        """打印后续步骤"""
        next_steps = """
╔══════════════════════════════════════════════════════════════╗
║                    🎉 设置完成！                              ║
╠══════════════════════════════════════════════════════════════╣
║ 后续步骤:                                                    ║
║                                                              ║
║ 1. 编辑 .env 文件，填入您的API密钥:                           ║
║    • OPENAI_API_KEY (必需)                                   ║
║    • ALPHA_VANTAGE_API_KEY (可选，免费500次/日)               ║
║    • REDDIT_CLIENT_ID/SECRET (可选，用于社交分析)             ║
║                                                              ║
║ 2. 测试系统:                                                 ║
║    python main_free.py --status                             ║
║                                                              ║
║ 3. 分析股票:                                                 ║
║    python main_free.py --analyze AAPL                       ║
║                                                              ║
║ 4. 批量分析:                                                 ║
║    python main_free.py --batch AAPL,MSFT,GOOGL             ║
║                                                              ║
║ 5. 启动Web界面 (第二阶段):                                   ║
║    python main_free.py --web                                ║
║                                                              ║
║ 📚 查看文档: docs/README.md                                  ║
║ 🆘 获取帮助: python main_free.py --help                     ║
╚══════════════════════════════════════════════════════════════╝
        """
        print(next_steps)
    
    def save_setup_log(self):
        """保存设置日志"""
        log_file = self.project_root / "logs" / "setup.log"
        
        with open(log_file, 'w', encoding='utf-8') as f:
            f.write("TradingAgents MVP免费版本设置日志\n")
            f.write("=" * 50 + "\n\n")
            
            for entry in self.setup_log:
                f.write(entry + "\n")
        
        self.log(f"设置日志已保存到: {log_file}")
    
    def run_setup(self) -> bool:
        """运行完整设置流程"""
        print("🚀 开始TradingAgents MVP免费版本设置...")
        print("=" * 60)
        
        # 检查环境
        if not self.check_python_version():
            return False
        
        if not self.check_required_commands():
            return False
        
        # 创建目录结构
        self.create_directories()
        
        # 安装依赖
        if not self.install_dependencies():
            return False
        
        # 设置配置文件
        self.setup_environment_file()
        self.create_config_files()
        
        # 测试系统
        if not self.test_system():
            self.log("系统测试失败，但基础设置已完成", "WARNING")
        
        # 保存日志
        self.save_setup_log()
        
        # 显示后续步骤
        self.print_next_steps()
        
        return True


def main():
    """主函数"""
    setup = TradingAgentsSetup()
    
    try:
        success = setup.run_setup()
        
        if success:
            print("\n🎉 TradingAgents MVP免费版本设置完成！")
            sys.exit(0)
        else:
            print("\n❌ 设置过程中遇到错误，请查看日志")
            sys.exit(1)
            
    except KeyboardInterrupt:
        print("\n\n👋 用户中断设置")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ 设置失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main() 