#!/usr/bin/env python3
"""
TradingAgents主程序 - AkShare集成版

基于AkShare免费数据源的完整交易智能体系统：
- 100%免费数据源，零API成本
- 覆盖A股、港股、美股、期货等全市场
- 实时行情、资金流向、技术分析
- 多智能体协作分析和决策
- 完整的风险管理和交易执行

成本对比：
- FinnHub版本: $197/月
- AkShare版本: $0/月 (节省100%)

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

import os
import sys
import asyncio
import argparse
import logging
from datetime import datetime
from typing import Dict, Any, List, Optional
import json

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from tradingagents.dataflows.akshare_adapter import create_akshare_adapter
from tradingagents.config.akshare_config import init_akshare_config
from tradingagents.agents.analysts.market_analyst_akshare import create_akshare_market_analyst

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/akshare_trading.log'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)


class AkShareTradingSystem:
    """
    基于AkShare的交易系统主控制器
    
    @description 统一管理所有智能体和数据流
    """
    
    def __init__(self, config_file: Optional[str] = None):
        """
        初始化交易系统
        
        @param {Optional[str]} config_file - 配置文件路径
        """
        # 初始化配置
        self.config = init_akshare_config(config_file)
        
        # 初始化数据适配器
        self.data_adapter = create_akshare_adapter(self.config.data_config)
        
        # 初始化智能体
        self.market_analyst = create_akshare_market_analyst()
        
        # 系统状态
        self.system_status = "INITIALIZED"
        self.last_analysis_time = None
        
        logger.info("AkShare交易系统初始化完成 - 100%免费数据源")
    
    async def run_market_analysis(self, analysis_type: str = "overview") -> Dict[str, Any]:
        """
        运行市场分析
        
        @param {str} analysis_type - 分析类型 ("overview", "sector", "breadth", "all")
        @returns {Dict[str, Any]} 分析结果
        """
        try:
            logger.info(f"开始市场分析: {analysis_type}")
            
            results = {
                "timestamp": datetime.now().isoformat(),
                "analysis_type": analysis_type,
                "system_version": "AkShare-2.0",
                "cost_info": {
                    "data_cost": "$0/月",
                    "savings_vs_finnhub": "$197/月 (100%节省)"
                }
            }
            
            if analysis_type in ["overview", "all"]:
                overview_result = await self.market_analyst.analyze_market_overview()
                results["market_overview"] = {
                    "sentiment": overview_result.market_sentiment,
                    "confidence": overview_result.confidence_score,
                    "key_insights": overview_result.key_insights,
                    "recommendations": overview_result.recommendations,
                    "technical_summary": overview_result.technical_summary,
                    "fund_flow_summary": overview_result.fund_flow_summary
                }
            
            if analysis_type in ["sector", "all"]:
                sector_result = await self.market_analyst.analyze_sector_rotation()
                results["sector_analysis"] = sector_result
            
            if analysis_type in ["breadth", "all"]:
                breadth_result = await self.market_analyst.analyze_market_breadth()
                results["market_breadth"] = breadth_result
            
            # 更新系统状态
            self.system_status = "ANALYSIS_COMPLETED"
            self.last_analysis_time = datetime.now()
            
            logger.info(f"市场分析完成: {analysis_type}")
            return results
            
        except Exception as e:
            logger.error(f"市场分析失败: {e}")
            self.system_status = "ANALYSIS_FAILED"
            return {
                "error": str(e),
                "timestamp": datetime.now().isoformat(),
                "analysis_type": analysis_type
            }
    
    async def get_stock_analysis(self, symbol: str, market: str = "auto") -> Dict[str, Any]:
        """
        获取个股分析
        
        @param {str} symbol - 股票代码
        @param {str} market - 市场类型
        @returns {Dict[str, Any]} 个股分析结果
        """
        try:
            logger.info(f"开始个股分析: {symbol}")
            
            # 获取实时行情
            realtime_data = self.data_adapter.stock.get_stock_realtime(symbol, market)
            
            # 获取历史数据
            history_data = self.data_adapter.stock.get_stock_history(symbol, "3m", market)
            
            # 基础分析
            analysis_result = {
                "symbol": symbol,
                "market": market,
                "timestamp": datetime.now().isoformat(),
                "realtime_data": realtime_data,
                "technical_analysis": self._analyze_stock_technical(history_data),
                "price_levels": self._calculate_price_levels(history_data),
                "volume_analysis": self._analyze_volume(history_data),
                "data_source": "AkShare-免费"
            }
            
            logger.info(f"个股分析完成: {symbol}")
            return analysis_result
            
        except Exception as e:
            logger.error(f"个股分析失败: {symbol} - {e}")
            return {
                "error": str(e),
                "symbol": symbol,
                "timestamp": datetime.now().isoformat()
            }
    
    async def get_market_overview(self) -> Dict[str, Any]:
        """
        获取市场概览
        
        @returns {Dict[str, Any]} 市场概览数据
        """
        try:
            logger.info("获取市场概览...")
            
            # 获取基础市场数据
            overview_data = self.data_adapter.get_market_overview()
            
            # 添加成本信息
            overview_data["cost_analysis"] = self.data_adapter.get_cost_analysis()
            
            # 添加系统状态
            overview_data["system_status"] = {
                "status": self.system_status,
                "last_analysis": self.last_analysis_time.isoformat() if self.last_analysis_time else None,
                "data_sources": ["AkShare-A股", "AkShare-港股", "AkShare-美股", "AkShare-期货"]
            }
            
            logger.info("市场概览获取完成")
            return overview_data
            
        except Exception as e:
            logger.error(f"获取市场概览失败: {e}")
            return {"error": str(e)}
    
    async def search_stocks(self, query: str) -> List[Dict[str, Any]]:
        """
        搜索股票
        
        @param {str} query - 搜索关键词
        @returns {List[Dict[str, Any]]} 搜索结果
        """
        try:
            logger.info(f"搜索股票: {query}")
            
            results = self.data_adapter.search_stock(query)
            
            logger.info(f"股票搜索完成: 找到{len(results)}只股票")
            return results
            
        except Exception as e:
            logger.error(f"股票搜索失败: {e}")
            return []
    
    def _analyze_stock_technical(self, history_data) -> Dict[str, Any]:
        """分析个股技术面"""
        try:
            if history_data.empty:
                return {}
            
            close_prices = history_data['close']
            
            # 移动平均线
            ma5 = close_prices.rolling(5).mean().iloc[-1]
            ma10 = close_prices.rolling(10).mean().iloc[-1]
            ma20 = close_prices.rolling(20).mean().iloc[-1] if len(history_data) >= 20 else None
            
            # 当前价格
            current_price = close_prices.iloc[-1]
            
            # 趋势判断
            trend = "NEUTRAL"
            if current_price > ma5 > ma10:
                trend = "BULLISH"
            elif current_price < ma5 < ma10:
                trend = "BEARISH"
            
            # RSI计算
            delta = close_prices.diff()
            gain = (delta.where(delta > 0, 0)).rolling(14).mean()
            loss = (-delta.where(delta < 0, 0)).rolling(14).mean()
            rs = gain / loss
            rsi = 100 - (100 / (1 + rs))
            current_rsi = rsi.iloc[-1] if not rsi.empty else 50
            
            return {
                "current_price": current_price,
                "ma5": ma5,
                "ma10": ma10,
                "ma20": ma20,
                "rsi": current_rsi,
                "trend": trend,
                "support_level": close_prices.min(),
                "resistance_level": close_prices.max()
            }
            
        except Exception as e:
            logger.error(f"技术分析失败: {e}")
            return {}
    
    def _calculate_price_levels(self, history_data) -> Dict[str, Any]:
        """计算价格关键位"""
        try:
            if history_data.empty:
                return {}
            
            high_prices = history_data['high']
            low_prices = history_data['low']
            close_prices = history_data['close']
            
            return {
                "support_1": low_prices.quantile(0.1),
                "support_2": low_prices.quantile(0.25),
                "resistance_1": high_prices.quantile(0.75),
                "resistance_2": high_prices.quantile(0.9),
                "pivot": (high_prices.max() + low_prices.min() + close_prices.iloc[-1]) / 3
            }
            
        except Exception as e:
            logger.error(f"计算价格关键位失败: {e}")
            return {}
    
    def _analyze_volume(self, history_data) -> Dict[str, Any]:
        """分析成交量"""
        try:
            if history_data.empty or 'volume' not in history_data.columns:
                return {}
            
            volumes = history_data['volume']
            
            return {
                "avg_volume": volumes.mean(),
                "current_volume": volumes.iloc[-1],
                "volume_ratio": volumes.iloc[-1] / volumes.mean(),
                "volume_trend": "HIGH" if volumes.iloc[-1] > volumes.mean() * 1.5 else "NORMAL"
            }
            
        except Exception as e:
            logger.error(f"成交量分析失败: {e}")
            return {}
    
    def get_system_info(self) -> Dict[str, Any]:
        """获取系统信息"""
        return {
            "system_name": "TradingAgents AkShare版",
            "version": "2.0",
            "data_source": "AkShare (100%免费)",
            "supported_markets": ["A股", "港股", "美股", "期货", "指数"],
            "cost_savings": "$197/月 (相比FinnHub)",
            "features": [
                "实时行情数据",
                "历史K线数据", 
                "资金流向分析",
                "技术指标计算",
                "板块轮动分析",
                "市场广度分析",
                "智能投资建议"
            ],
            "status": self.system_status,
            "last_analysis": self.last_analysis_time.isoformat() if self.last_analysis_time else None
        }


async def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="TradingAgents AkShare版 - 100%免费金融数据分析系统")
    parser.add_argument("--action", choices=["analysis", "stock", "search", "overview", "info"], 
                       default="overview", help="执行的操作")
    parser.add_argument("--type", choices=["overview", "sector", "breadth", "all"], 
                       default="overview", help="分析类型")
    parser.add_argument("--symbol", type=str, help="股票代码")
    parser.add_argument("--query", type=str, help="搜索关键词")
    parser.add_argument("--market", choices=["auto", "a_stock", "hk_stock", "us_stock"], 
                       default="auto", help="市场类型")
    parser.add_argument("--config", type=str, help="配置文件路径")
    parser.add_argument("--output", type=str, help="输出文件路径")
    
    args = parser.parse_args()
    
    # 确保日志目录存在
    os.makedirs("logs", exist_ok=True)
    
    try:
        # 初始化系统
        print("🚀 初始化TradingAgents AkShare版...")
        system = AkShareTradingSystem(args.config)
        
        print("💰 成本对比:")
        print("   FinnHub版本: $197/月")
        print("   AkShare版本: $0/月")
        print("   💸 节省: $197/月 (100%)")
        print()
        
        result = None
        
        if args.action == "analysis":
            print(f"📊 执行市场分析: {args.type}")
            result = await system.run_market_analysis(args.type)
            
        elif args.action == "stock":
            if not args.symbol:
                print("❌ 错误: 请提供股票代码 (--symbol)")
                return
            print(f"📈 分析个股: {args.symbol}")
            result = await system.get_stock_analysis(args.symbol, args.market)
            
        elif args.action == "search":
            if not args.query:
                print("❌ 错误: 请提供搜索关键词 (--query)")
                return
            print(f"🔍 搜索股票: {args.query}")
            result = await system.search_stocks(args.query)
            
        elif args.action == "overview":
            print("🌍 获取市场概览...")
            result = await system.get_market_overview()
            
        elif args.action == "info":
            print("ℹ️ 系统信息:")
            result = system.get_system_info()
        
        # 输出结果
        if result:
            if args.output:
                with open(args.output, 'w', encoding='utf-8') as f:
                    json.dump(result, f, ensure_ascii=False, indent=2)
                print(f"✅ 结果已保存到: {args.output}")
            else:
                print("\n📋 分析结果:")
                print(json.dumps(result, ensure_ascii=False, indent=2))
        
        print("\n🎉 AkShare版TradingAgents运行完成!")
        print("💡 提示: 所有数据完全免费，无API成本!")
        
    except KeyboardInterrupt:
        print("\n⏹️ 用户中断操作")
    except Exception as e:
        logger.error(f"系统运行失败: {e}")
        print(f"❌ 系统错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    # 运行主程序
    asyncio.run(main())