#!/usr/bin/env python3
"""
修复investment_debate_state错误的快速脚本
============================================

修复状态兼容性问题，确保新旧AgentState版本兼容

@author TradingAgents团队
@version Fix-1.0
"""

import os
import sys
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))


def check_current_issue():
    """检查当前问题状态"""
    
    print("🔍 检查当前investment_debate_state问题...")
    
    try:
        # 测试导入
        from tradingagents.agents.state import AgentState
        print("✅ 新版AgentState导入成功")
        
        # 检查是否有兼容性字段
        test_state = AgentState()
        
        if hasattr(test_state, 'investment_debate_state'):
            print("✅ investment_debate_state字段存在")
        else:
            print("❌ investment_debate_state字段缺失")
            return False
            
        if hasattr(test_state, 'risk_debate_state'):
            print("✅ risk_debate_state字段存在")
        else:
            print("❌ risk_debate_state字段缺失")
            return False
            
        # 测试字典访问
        try:
            test_state['investment_debate_state'] = {}
            print("✅ 字典式访问正常")
        except Exception as e:
            print(f"❌ 字典式访问失败: {e}")
            return False
            
        return True
        
    except Exception as e:
        print(f"❌ 检查失败: {e}")
        return False


def run_quick_test():
    """运行快速测试"""
    
    print("\n🧪 运行快速分析测试...")
    
    try:
        from tradingagents.hybrid_config import create_hybrid_config
        from tradingagents.dataflows.free_alternatives import FreeDataManager
        from tradingagents.agents.state import AgentState
        from datetime import datetime
        
        # 创建最小配置
        config_manager = create_hybrid_config("development")
        
        # 创建测试状态
        state = AgentState(
            ticker="TEST",
            company_of_interest="TEST", 
            trade_date=datetime.now().strftime('%Y-%m-%d'),
            
            # 关键：包含所有必要的兼容性字段
            investment_debate_state={
                'bull_history': '',
                'bear_history': '',
                'history': '',
                'current_response': '',
                'judge_decision': '',
                'count': 0
            },
            risk_debate_state={
                'risky_history': '',
                'safe_history': '',
                'neutral_history': '',
                'history': '',
                'latest_speaker': '',
                'current_risky_response': '',
                'current_safe_response': '',
                'current_neutral_response': '',
                'judge_decision': '',
                'count': 0
            },
            market_report='',
            sentiment_report='',
            news_report='',
            fundamentals_report='',
            investment_plan='',
            trader_investment_plan='',
            final_trade_decision=''
        )
        
        print("✅ 兼容状态创建成功")
        
        # 测试关键访问
        try:
            debate_state = state['investment_debate_state']
            bull_history = debate_state['bull_history']
            print("✅ 嵌套字典访问成功")
        except Exception as e:
            print(f"❌ 嵌套访问失败: {e}")
            return False
            
        return True
        
    except Exception as e:
        print(f"❌ 快速测试失败: {e}")
        return False


def print_solution_summary():
    """打印解决方案摘要"""
    
    print("\n" + "=" * 60)
    print("🛠️  解决方案摘要")
    print("=" * 60)
    
    print("""
🔧 问题原因:
   - 系统中存在两个不同的AgentState定义
   - 新版本(简化)缺少investment_debate_state等字段
   - 原始图结构期望完整版本的状态格式

✅ 修复措施:
   1. 在新版AgentState中添加兼容性字段
   2. 在main_hybrid.py中初始化所有必要字段
   3. 确保字典式访问和属性访问都正常工作

🎯 测试建议:
   python main_hybrid.py MSTR
   python debug_state_compatibility.py
   
⚠️  注意事项:
   - 如果仍有问题，请检查图结构是否使用了正确的状态类
   - 确保所有必要的字段都已正确初始化
   """)


def main():
    """主修复函数"""
    
    print("🔧 investment_debate_state错误修复脚本")
    print("=" * 50)
    
    # 步骤1: 检查当前状态
    current_ok = check_current_issue()
    
    # 步骤2: 运行快速测试
    test_ok = run_quick_test()
    
    # 步骤3: 打印摘要
    print_solution_summary()
    
    print("\n📊 修复结果:")
    print(f"状态检查: {'✅ 通过' if current_ok else '❌ 失败'}")
    print(f"快速测试: {'✅ 通过' if test_ok else '❌ 失败'}")
    
    if current_ok and test_ok:
        print("\n🎉 修复成功！investment_debate_state错误已解决。")
        print("现在可以重新测试: python main_hybrid.py MSTR")
        return 0
    else:
        print("\n❌ 修复未完全成功，需要进一步调试。")
        return 1


if __name__ == "__main__":
    exit(main())