#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
增强版优先级算法测试脚本
测试新的优先级算法在起承转合辩论系统中的表现
"""

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

from jixia.debates.qi_cheng_zhuan_he_debate import QiChengZhuanHeDebateSystem, DebateStage
from jixia.debates.enhanced_priority_algorithm import EnhancedPriorityAlgorithm

def test_enhanced_priority_algorithm():
    """测试增强版优先级算法"""
    print("🧪 开始测试增强版优先级算法")
    print("=" * 50)
    
    # 创建辩论系统
    debate_system = QiChengZhuanHeDebateSystem()
    
    # 模拟辩论场景
    test_scenarios = [
        {
            "name": "起阶段开始",
            "stage": DebateStage.QI,
            "progress": 1,
            "history": []
        },
        {
            "name": "承阶段中期",
            "stage": DebateStage.CHENG,
            "progress": 3,
            "history": [
                {"speaker": "正1", "content": "AI投资具有巨大潜力", "timestamp": "2024-01-01T10:00:00"},
                {"speaker": "反1", "content": "但风险也很高", "timestamp": "2024-01-01T10:01:00"}
            ]
        },
        {
            "name": "转阶段激烈辩论",
            "stage": DebateStage.ZHUAN,
            "progress": 5,
            "history": [
                {"speaker": "正2", "content": "数据显示AI投资回报率很高", "timestamp": "2024-01-01T10:02:00"},
                {"speaker": "反2", "content": "这些数据可能有偏差", "timestamp": "2024-01-01T10:03:00"},
                {"speaker": "正3", "content": "我们有严格的风控措施", "timestamp": "2024-01-01T10:04:00"},
                {"speaker": "反3", "content": "风控措施并不能完全避免风险", "timestamp": "2024-01-01T10:05:00"}
            ]
        },
        {
            "name": "合阶段总结",
            "stage": DebateStage.HE,
            "progress": 2,
            "history": [
                {"speaker": "正4", "content": "综合来看，AI投资利大于弊", "timestamp": "2024-01-01T10:06:00"},
                {"speaker": "反4", "content": "我们需要更谨慎的态度", "timestamp": "2024-01-01T10:07:00"}
            ]
        }
    ]
    
    for i, scenario in enumerate(test_scenarios, 1):
        print(f"\n📋 测试场景 {i}: {scenario['name']}")
        print("-" * 30)
        
        # 设置辩论状态
        debate_system.context.current_stage = scenario['stage']
        debate_system.context.stage_progress = scenario['progress']
        debate_system.context.debate_history = scenario['history']
        
        # 获取推荐发言者
        try:
            recommended_speaker = debate_system._get_priority_speaker()
            analysis = debate_system.context.last_priority_analysis
            
            print(f"🎯 推荐发言者: {recommended_speaker}")
            print(f"📊 优先级分数: {analysis.get('priority_score', 'N/A'):.3f}")
            
            if 'analysis' in analysis:
                detailed_analysis = analysis['analysis']
                print(f"🔍 详细分析:")
                
                # 显示推荐发言者的详细信息
                if recommended_speaker in detailed_analysis:
                    speaker_info = detailed_analysis[recommended_speaker]
                    print(f"   - 发言者: {recommended_speaker}")
                    print(f"   - 优先级分数: {speaker_info.get('priority_score', 'N/A'):.3f}")
                    print(f"   - 分析时间: {speaker_info.get('analysis_timestamp', 'N/A')}")
                    
                    profile = speaker_info.get('profile')
                    if profile:
                        print(f"   - 团队: {profile.team}")
                        print(f"   - 发言次数: {profile.total_speech_count}")
                        print(f"   - 当前能量: {profile.current_energy:.2f}")
                        print(f"   - 辩论风格: {profile.debate_style}")
                
                # 显示所有发言者的分数排名
                print(f"\n   📊 所有发言者排名:")
                sorted_speakers = sorted(detailed_analysis.items(), 
                                       key=lambda x: x[1].get('priority_score', 0), 
                                       reverse=True)
                for rank, (speaker, info) in enumerate(sorted_speakers[:5], 1):
                    score = info.get('priority_score', 0)
                    print(f"      {rank}. {speaker}: {score:.3f}")
                
        except Exception as e:
            print(f"❌ 测试失败: {e}")
            import traceback
            traceback.print_exc()
    
    print("\n" + "=" * 50)
    print("✅ 增强版优先级算法测试完成")

def test_algorithm_performance():
    """测试算法性能"""
    print("\n⚡ 性能测试")
    print("-" * 20)
    
    import time
    
    algorithm = EnhancedPriorityAlgorithm()
    available_speakers = ["正1", "正2", "正3", "正4", "反1", "反2", "反3", "反4"]
    
    context = {
        "current_stage": "承",
        "stage_progress": 3,
        "max_progress": 6,
        "time_remaining": 0.5,
        "topic_keywords": ["AI", "投资", "风险"],
        "positive_team_score": 0.6,
        "negative_team_score": 0.4,
        "positive_recent_speeches": 3,
        "negative_recent_speeches": 2
    }
    
    recent_speeches = [
        {"speaker": "正1", "content": "AI技术发展迅速"},
        {"speaker": "反1", "content": "但存在不确定性"}
    ]
    
    # 性能测试
    start_time = time.time()
    iterations = 100
    
    for _ in range(iterations):
        speaker, score, analysis = algorithm.get_next_speaker(
            available_speakers, context, recent_speeches
        )
    
    end_time = time.time()
    avg_time = (end_time - start_time) / iterations * 1000  # 转换为毫秒
    
    print(f"📈 平均处理时间: {avg_time:.2f}ms")
    print(f"🔄 总迭代次数: {iterations}")
    print(f"⚡ 处理速度: {1000/avg_time:.0f} 次/秒")

if __name__ == "__main__":
    test_enhanced_priority_algorithm()
    test_algorithm_performance()