#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
优化的辩论流程控制系统 v2.1.0
改进阶段转换和发言权争夺逻辑
"""

import asyncio
import json
import time
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional, Tuple, Callable
from dataclasses import dataclass, field
from enum import Enum
from collections import defaultdict, deque
import threading
import queue

class DebateStage(Enum):
    """辩论阶段枚举"""
    QI = "起"      # 八仙按先天八卦顺序
    CHENG = "承"   # 雁阵式承接
    ZHUAN = "转"   # 自由辩论（36次handoff）
    HE = "合"      # 交替总结

class FlowControlMode(Enum):
    """流程控制模式"""
    STRICT = "严格模式"     # 严格按规则执行
    ADAPTIVE = "自适应模式"  # 根据辩论质量调整
    DYNAMIC = "动态模式"    # 实时响应辩论状态

class TransitionTrigger(Enum):
    """阶段转换触发条件"""
    TIME_BASED = "时间触发"
    PROGRESS_BASED = "进度触发"
    QUALITY_BASED = "质量触发"
    CONSENSUS_BASED = "共识触发"
    EMERGENCY = "紧急触发"

class SpeakerSelectionStrategy(Enum):
    """发言者选择策略"""
    PRIORITY_ALGORITHM = "优先级算法"
    ROUND_ROBIN = "轮询"
    RANDOM_WEIGHTED = "加权随机"
    CONTEXT_AWARE = "上下文感知"
    COMPETITIVE = "竞争模式"

@dataclass
class FlowControlConfig:
    """流程控制配置"""
    mode: FlowControlMode = FlowControlMode.ADAPTIVE
    transition_triggers: List[TransitionTrigger] = field(default_factory=lambda: [TransitionTrigger.PROGRESS_BASED, TransitionTrigger.QUALITY_BASED])
    speaker_selection_strategy: SpeakerSelectionStrategy = SpeakerSelectionStrategy.CONTEXT_AWARE
    min_stage_duration: int = 60  # 秒
    max_stage_duration: int = 900  # 秒
    quality_threshold: float = 0.6  # 质量阈值
    participation_balance_threshold: float = 0.3  # 参与平衡阈值
    emergency_intervention_enabled: bool = True
    auto_stage_transition: bool = True
    speaker_timeout: int = 30  # 发言超时时间

@dataclass
class StageMetrics:
    """阶段指标"""
    start_time: datetime
    duration: float = 0.0
    speech_count: int = 0
    quality_score: float = 0.0
    participation_balance: float = 0.0
    engagement_level: float = 0.0
    topic_coherence: float = 0.0
    conflict_intensity: float = 0.0
    speaker_distribution: Dict[str, int] = field(default_factory=dict)
    transition_readiness: float = 0.0

@dataclass
class SpeakerRequest:
    """发言请求"""
    speaker: str
    priority: float
    timestamp: datetime
    reason: str
    urgency_level: int = 1  # 1-5
    estimated_duration: int = 30  # 秒
    topic_relevance: float = 1.0

@dataclass
class FlowEvent:
    """流程事件"""
    event_type: str
    timestamp: datetime
    data: Dict[str, Any]
    source: str
    priority: int = 1

class OptimizedDebateFlowController:
    """优化的辩论流程控制器"""
    
    def __init__(self, config: FlowControlConfig = None):
        self.config = config or FlowControlConfig()
        
        # 当前状态
        self.current_stage = DebateStage.QI
        self.stage_progress = 0
        self.total_handoffs = 0
        self.current_speaker: Optional[str] = None
        self.debate_start_time = datetime.now()
        
        # 阶段配置
        self.stage_configs = {
            DebateStage.QI: {
                "max_progress": 8,
                "min_duration": 120,
                "max_duration": 600,
                "speaker_order": ["吕洞宾", "何仙姑", "铁拐李", "汉钟离", "曹国舅", "韩湘子", "蓝采和", "张果老"],
                "selection_strategy": SpeakerSelectionStrategy.ROUND_ROBIN
            },
            DebateStage.CHENG: {
                "max_progress": 8,
                "min_duration": 180,
                "max_duration": 600,
                "speaker_order": ["正1", "正2", "正3", "正4", "反1", "反2", "反3", "反4"],
                "selection_strategy": SpeakerSelectionStrategy.ROUND_ROBIN
            },
            DebateStage.ZHUAN: {
                "max_progress": 36,
                "min_duration": 300,
                "max_duration": 900,
                "speaker_order": ["正1", "正2", "正3", "正4", "反1", "反2", "反3", "反4"],
                "selection_strategy": SpeakerSelectionStrategy.CONTEXT_AWARE
            },
            DebateStage.HE: {
                "max_progress": 8,
                "min_duration": 120,
                "max_duration": 480,
                "speaker_order": ["反1", "正1", "反2", "正2", "反3", "正3", "反4", "正4"],
                "selection_strategy": SpeakerSelectionStrategy.ROUND_ROBIN
            }
        }
        
        # 阶段指标
        self.stage_metrics: Dict[DebateStage, StageMetrics] = {}
        self.current_stage_metrics = StageMetrics(start_time=datetime.now())
        
        # 发言请求队列
        self.speaker_request_queue = queue.PriorityQueue()
        self.pending_requests: Dict[str, SpeakerRequest] = {}
        
        # 事件系统
        self.event_queue = queue.Queue()
        self.event_handlers: Dict[str, List[Callable]] = defaultdict(list)
        
        # 历史记录
        self.debate_history: List[Dict] = []
        self.stage_transition_history: List[Dict] = []
        self.speaker_performance: Dict[str, Dict] = defaultdict(dict)
        
        # 实时监控
        self.monitoring_active = False
        self.monitoring_thread: Optional[threading.Thread] = None
        
        # 流程锁
        self.flow_lock = threading.RLock()
        
        # 初始化当前阶段指标
        self._initialize_stage_metrics()
        
    def _initialize_stage_metrics(self):
        """初始化阶段指标"""
        self.current_stage_metrics = StageMetrics(
            start_time=datetime.now(),
            speaker_distribution={}
        )
        
    def get_current_speaker(self) -> Optional[str]:
        """获取当前发言者"""
        with self.flow_lock:
            config = self.stage_configs[self.current_stage]
            strategy = config.get("selection_strategy", self.config.speaker_selection_strategy)
            
            if strategy == SpeakerSelectionStrategy.ROUND_ROBIN:
                return self._get_round_robin_speaker()
            elif strategy == SpeakerSelectionStrategy.CONTEXT_AWARE:
                return self._get_context_aware_speaker()
            elif strategy == SpeakerSelectionStrategy.PRIORITY_ALGORITHM:
                return self._get_priority_speaker()
            elif strategy == SpeakerSelectionStrategy.COMPETITIVE:
                return self._get_competitive_speaker()
            else:
                return self._get_round_robin_speaker()
    
    def _get_round_robin_speaker(self) -> str:
        """轮询方式获取发言者"""
        config = self.stage_configs[self.current_stage]
        speaker_order = config["speaker_order"]
        return speaker_order[self.stage_progress % len(speaker_order)]
    
    def _get_context_aware_speaker(self) -> Optional[str]:
        """上下文感知方式获取发言者"""
        # 检查是否有紧急发言请求
        if not self.speaker_request_queue.empty():
            try:
                priority, request = self.speaker_request_queue.get_nowait()
                if request.urgency_level >= 4:  # 高紧急度
                    return request.speaker
                else:
                    # 重新放回队列
                    self.speaker_request_queue.put((priority, request))
            except queue.Empty:
                pass
        
        # 分析当前上下文
        context = self._analyze_current_context()
        
        # 根据上下文选择最合适的发言者
        available_speakers = self.stage_configs[self.current_stage]["speaker_order"]
        best_speaker = None
        best_score = -1
        
        for speaker in available_speakers:
            score = self._calculate_speaker_context_score(speaker, context)
            if score > best_score:
                best_score = score
                best_speaker = speaker
        
        return best_speaker
    
    def _get_priority_speaker(self) -> Optional[str]:
        """优先级算法获取发言者"""
        # 这里可以集成现有的优先级算法
        # 暂时使用简化版本
        return self._get_context_aware_speaker()
    
    def _get_competitive_speaker(self) -> Optional[str]:
        """竞争模式获取发言者"""
        # 让发言者竞争发言权
        if not self.speaker_request_queue.empty():
            try:
                priority, request = self.speaker_request_queue.get_nowait()
                return request.speaker
            except queue.Empty:
                pass
        
        return self._get_round_robin_speaker()
    
    def request_speaking_turn(self, speaker: str, reason: str, urgency: int = 1, 
                            estimated_duration: int = 30, topic_relevance: float = 1.0):
        """请求发言权"""
        request = SpeakerRequest(
            speaker=speaker,
            priority=self._calculate_request_priority(speaker, reason, urgency, topic_relevance),
            timestamp=datetime.now(),
            reason=reason,
            urgency_level=urgency,
            estimated_duration=estimated_duration,
            topic_relevance=topic_relevance
        )
        
        # 使用负优先级，因为PriorityQueue是最小堆
        self.speaker_request_queue.put((-request.priority, request))
        self.pending_requests[speaker] = request
        
        # 触发事件
        self._emit_event("speaker_request", {
            "speaker": speaker,
            "reason": reason,
            "urgency": urgency,
            "priority": request.priority
        })
    
    def _calculate_request_priority(self, speaker: str, reason: str, urgency: int, 
                                  topic_relevance: float) -> float:
        """计算发言请求优先级"""
        base_priority = urgency * 10
        
        # 主题相关性加权
        relevance_bonus = topic_relevance * 5
        
        # 发言频率调整
        speaker_count = self.current_stage_metrics.speaker_distribution.get(speaker, 0)
        frequency_penalty = speaker_count * 2
        
        # 时间因素
        time_factor = 1.0
        if self.current_speaker and self.current_speaker != speaker:
            time_factor = 1.2  # 鼓励轮换
        
        priority = (base_priority + relevance_bonus - frequency_penalty) * time_factor
        return max(0.1, priority)
    
    def _analyze_current_context(self) -> Dict[str, Any]:
        """分析当前辩论上下文"""
        recent_speeches = self.debate_history[-5:] if self.debate_history else []
        
        context = {
            "stage": self.current_stage.value,
            "progress": self.stage_progress,
            "recent_speakers": [speech.get("speaker") for speech in recent_speeches],
            "topic_drift": self._calculate_topic_drift(),
            "emotional_intensity": self._calculate_emotional_intensity(),
            "argument_balance": self._calculate_argument_balance(),
            "time_pressure": self._calculate_time_pressure(),
            "participation_balance": self._calculate_participation_balance()
        }
        
        return context
    
    def _calculate_speaker_context_score(self, speaker: str, context: Dict[str, Any]) -> float:
        """计算发言者在当前上下文下的适合度分数"""
        score = 0.0
        
        # 避免连续发言
        recent_speakers = context.get("recent_speakers", [])
        if speaker in recent_speakers[-2:]:
            score -= 10
        
        # 参与平衡
        speaker_count = self.current_stage_metrics.speaker_distribution.get(speaker, 0)
        avg_count = sum(self.current_stage_metrics.speaker_distribution.values()) / max(1, len(self.current_stage_metrics.speaker_distribution))
        if speaker_count < avg_count:
            score += 5
        
        # 队伍平衡
        if self.current_stage == DebateStage.ZHUAN:
            positive_count = sum(1 for s in recent_speakers if "正" in s)
            negative_count = sum(1 for s in recent_speakers if "反" in s)
            
            if "正" in speaker and positive_count < negative_count:
                score += 3
            elif "反" in speaker and negative_count < positive_count:
                score += 3
        
        # 时间压力响应
        time_pressure = context.get("time_pressure", 0)
        if time_pressure > 0.7 and speaker.endswith("1"):  # 主力发言者
            score += 5
        
        # 检查发言请求
        if speaker in self.pending_requests:
            request = self.pending_requests[speaker]
            score += request.urgency_level * 2
            score += request.topic_relevance * 3
        
        return score
    
    def advance_stage(self, force: bool = False) -> bool:
        """推进辩论阶段"""
        with self.flow_lock:
            if not force and not self._should_advance_stage():
                return False
            
            # 记录当前阶段结束
            self._finalize_current_stage()
            
            # 转换到下一阶段
            success = self._transition_to_next_stage()
            
            if success:
                # 初始化新阶段
                self._initialize_new_stage()
                
                # 触发事件
                self._emit_event("stage_advanced", {
                    "from_stage": self.current_stage.value,
                    "to_stage": self.current_stage.value,
                    "progress": self.stage_progress,
                    "forced": force
                })
            
            return success
    
    def _should_advance_stage(self) -> bool:
        """判断是否应该推进阶段"""
        config = self.stage_configs[self.current_stage]
        
        # 检查进度触发
        if TransitionTrigger.PROGRESS_BASED in self.config.transition_triggers:
            if self.stage_progress >= config["max_progress"] - 1:
                return True
        
        # 检查时间触发
        if TransitionTrigger.TIME_BASED in self.config.transition_triggers:
            stage_duration = (datetime.now() - self.current_stage_metrics.start_time).total_seconds()
            if stage_duration >= config.get("max_duration", 600):
                return True
        
        # 检查质量触发
        if TransitionTrigger.QUALITY_BASED in self.config.transition_triggers:
            if (self.current_stage_metrics.quality_score >= self.config.quality_threshold and 
                self.stage_progress >= config["max_progress"] // 2):
                return True
        
        # 检查共识触发
        if TransitionTrigger.CONSENSUS_BASED in self.config.transition_triggers:
            if self.current_stage_metrics.transition_readiness >= 0.8:
                return True
        
        return False
    
    def _finalize_current_stage(self):
        """结束当前阶段"""
        # 更新阶段指标
        self.current_stage_metrics.duration = (datetime.now() - self.current_stage_metrics.start_time).total_seconds()
        
        # 保存阶段指标
        self.stage_metrics[self.current_stage] = self.current_stage_metrics
        
        # 记录阶段转换历史
        self.stage_transition_history.append({
            "stage": self.current_stage.value,
            "start_time": self.current_stage_metrics.start_time.isoformat(),
            "duration": self.current_stage_metrics.duration,
            "speech_count": self.current_stage_metrics.speech_count,
            "quality_score": self.current_stage_metrics.quality_score,
            "participation_balance": self.current_stage_metrics.participation_balance
        })
    
    def _transition_to_next_stage(self) -> bool:
        """转换到下一阶段"""
        stage_transitions = {
            DebateStage.QI: DebateStage.CHENG,
            DebateStage.CHENG: DebateStage.ZHUAN,
            DebateStage.ZHUAN: DebateStage.HE,
            DebateStage.HE: None
        }
        
        next_stage = stage_transitions.get(self.current_stage)
        if next_stage:
            self.current_stage = next_stage
            self.stage_progress = 0
            return True
        else:
            # 辩论结束
            self._emit_event("debate_finished", {
                "total_duration": (datetime.now() - self.debate_start_time).total_seconds(),
                "total_handoffs": self.total_handoffs,
                "stages_completed": len(self.stage_metrics)
            })
            return False
    
    def _initialize_new_stage(self):
        """初始化新阶段"""
        self._initialize_stage_metrics()
        
        # 清空发言请求队列
        while not self.speaker_request_queue.empty():
            try:
                self.speaker_request_queue.get_nowait()
            except queue.Empty:
                break
        
        self.pending_requests.clear()
    
    def record_speech(self, speaker: str, message: str, metadata: Dict[str, Any] = None):
        """记录发言"""
        with self.flow_lock:
            speech_record = {
                "timestamp": datetime.now().isoformat(),
                "stage": self.current_stage.value,
                "stage_progress": self.stage_progress,
                "speaker": speaker,
                "message": message,
                "total_handoffs": self.total_handoffs,
                "metadata": metadata or {}
            }
            
            self.debate_history.append(speech_record)
            self.current_speaker = speaker
            
            # 更新阶段指标
            self._update_stage_metrics(speaker, message)
            
            # 如果是转阶段，增加handoff计数
            if self.current_stage == DebateStage.ZHUAN:
                self.total_handoffs += 1
            
            # 推进进度
            self.stage_progress += 1
            
            # 移除已完成的发言请求
            if speaker in self.pending_requests:
                del self.pending_requests[speaker]
            
            # 触发事件
            self._emit_event("speech_recorded", {
                "speaker": speaker,
                "stage": self.current_stage.value,
                "progress": self.stage_progress
            })
    
    def _update_stage_metrics(self, speaker: str, message: str):
        """更新阶段指标"""
        # 更新发言计数
        self.current_stage_metrics.speech_count += 1
        
        # 更新发言者分布
        if speaker not in self.current_stage_metrics.speaker_distribution:
            self.current_stage_metrics.speaker_distribution[speaker] = 0
        self.current_stage_metrics.speaker_distribution[speaker] += 1
        
        # 计算参与平衡度
        self.current_stage_metrics.participation_balance = self._calculate_participation_balance()
        
        # 计算质量分数（简化版本）
        self.current_stage_metrics.quality_score = self._calculate_quality_score(message)
        
        # 计算转换准备度
        self.current_stage_metrics.transition_readiness = self._calculate_transition_readiness()
    
    def _calculate_topic_drift(self) -> float:
        """计算主题偏移度"""
        # 简化实现
        return 0.1
    
    def _calculate_emotional_intensity(self) -> float:
        """计算情绪强度"""
        # 简化实现
        return 0.5
    
    def _calculate_argument_balance(self) -> float:
        """计算论点平衡度"""
        # 简化实现
        return 0.7
    
    def _calculate_time_pressure(self) -> float:
        """计算时间压力"""
        config = self.stage_configs[self.current_stage]
        stage_duration = (datetime.now() - self.current_stage_metrics.start_time).total_seconds()
        max_duration = config.get("max_duration", 600)
        return min(1.0, stage_duration / max_duration)
    
    def _calculate_participation_balance(self) -> float:
        """计算参与平衡度"""
        if not self.current_stage_metrics.speaker_distribution:
            return 1.0
        
        counts = list(self.current_stage_metrics.speaker_distribution.values())
        if not counts:
            return 1.0
        
        avg_count = sum(counts) / len(counts)
        variance = sum((count - avg_count) ** 2 for count in counts) / len(counts)
        
        # 归一化到0-1范围
        balance = 1.0 / (1.0 + variance)
        return balance
    
    def _calculate_quality_score(self, message: str) -> float:
        """计算质量分数"""
        # 简化实现，基于消息长度和关键词
        base_score = min(1.0, len(message) / 100)
        
        # 检查关键词
        quality_keywords = ["因为", "所以", "但是", "然而", "数据", "证据", "分析"]
        keyword_bonus = sum(0.1 for keyword in quality_keywords if keyword in message)
        
        return min(1.0, base_score + keyword_bonus)
    
    def _calculate_transition_readiness(self) -> float:
        """计算转换准备度"""
        # 综合多个因素
        progress_factor = self.stage_progress / self.stage_configs[self.current_stage]["max_progress"]
        quality_factor = self.current_stage_metrics.quality_score
        balance_factor = self.current_stage_metrics.participation_balance
        
        readiness = (progress_factor * 0.4 + quality_factor * 0.3 + balance_factor * 0.3)
        return min(1.0, readiness)
    
    def _emit_event(self, event_type: str, data: Dict[str, Any]):
        """发出事件"""
        event = FlowEvent(
            event_type=event_type,
            timestamp=datetime.now(),
            data=data,
            source="flow_controller"
        )
        
        self.event_queue.put(event)
        
        # 调用事件处理器
        for handler in self.event_handlers.get(event_type, []):
            try:
                handler(event)
            except Exception as e:
                print(f"事件处理器错误: {e}")
    
    def add_event_handler(self, event_type: str, handler: Callable):
        """添加事件处理器"""
        self.event_handlers[event_type].append(handler)
    
    def get_flow_status(self) -> Dict[str, Any]:
        """获取流程状态"""
        return {
            "current_stage": self.current_stage.value,
            "stage_progress": self.stage_progress,
            "total_handoffs": self.total_handoffs,
            "current_speaker": self.current_speaker,
            "stage_metrics": {
                "duration": (datetime.now() - self.current_stage_metrics.start_time).total_seconds(),
                "speech_count": self.current_stage_metrics.speech_count,
                "quality_score": self.current_stage_metrics.quality_score,
                "participation_balance": self.current_stage_metrics.participation_balance,
                "transition_readiness": self.current_stage_metrics.transition_readiness
            },
            "pending_requests": len(self.pending_requests),
            "config": {
                "mode": self.config.mode.value,
                "auto_transition": self.config.auto_stage_transition,
                "quality_threshold": self.config.quality_threshold
            }
        }
    
    def save_flow_data(self, filename: str = "debate_flow_data.json"):
        """保存流程数据"""
        flow_data = {
            "config": {
                "mode": self.config.mode.value,
                "transition_triggers": [t.value for t in self.config.transition_triggers],
                "speaker_selection_strategy": self.config.speaker_selection_strategy.value,
                "quality_threshold": self.config.quality_threshold,
                "auto_stage_transition": self.config.auto_stage_transition
            },
            "current_state": {
                "stage": self.current_stage.value,
                "progress": self.stage_progress,
                "total_handoffs": self.total_handoffs,
                "current_speaker": self.current_speaker,
                "debate_start_time": self.debate_start_time.isoformat()
            },
            "stage_metrics": {
                stage.value: {
                    "start_time": metrics.start_time.isoformat(),
                    "duration": metrics.duration,
                    "speech_count": metrics.speech_count,
                    "quality_score": metrics.quality_score,
                    "participation_balance": metrics.participation_balance,
                    "speaker_distribution": metrics.speaker_distribution
                } for stage, metrics in self.stage_metrics.items()
            },
            "current_stage_metrics": {
                "start_time": self.current_stage_metrics.start_time.isoformat(),
                "duration": (datetime.now() - self.current_stage_metrics.start_time).total_seconds(),
                "speech_count": self.current_stage_metrics.speech_count,
                "quality_score": self.current_stage_metrics.quality_score,
                "participation_balance": self.current_stage_metrics.participation_balance,
                "speaker_distribution": self.current_stage_metrics.speaker_distribution,
                "transition_readiness": self.current_stage_metrics.transition_readiness
            },
            "debate_history": self.debate_history,
            "stage_transition_history": self.stage_transition_history,
            "timestamp": datetime.now().isoformat()
        }
        
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(flow_data, f, ensure_ascii=False, indent=2)
        
        print(f"✅ 流程数据已保存到 {filename}")

def main():
    """测试优化的辩论流程控制系统"""
    print("🎭 测试优化的辩论流程控制系统")
    print("=" * 50)
    
    # 创建配置
    config = FlowControlConfig(
        mode=FlowControlMode.ADAPTIVE,
        transition_triggers=[TransitionTrigger.PROGRESS_BASED, TransitionTrigger.QUALITY_BASED],
        speaker_selection_strategy=SpeakerSelectionStrategy.CONTEXT_AWARE,
        auto_stage_transition=True
    )
    
    # 创建流程控制器
    controller = OptimizedDebateFlowController(config)
    
    # 添加事件处理器
    def on_stage_advanced(event):
        print(f"🎭 阶段转换: {event.data}")
    
    def on_speech_recorded(event):
        print(f"🗣️ 发言记录: {event.data['speaker']} 在 {event.data['stage']} 阶段")
    
    controller.add_event_handler("stage_advanced", on_stage_advanced)
    controller.add_event_handler("speech_recorded", on_speech_recorded)
    
    # 模拟辩论流程
    test_speeches = [
        ("吕洞宾", "我认为AI投资具有巨大的潜力和机会。"),
        ("何仙姑", "但我们也需要考虑其中的风险因素。"),
        ("铁拐李", "数据显示AI行业的增长率确实很高。"),
        ("汉钟离", "然而市场波动性也不容忽视。")
    ]
    
    print("\n📋 开始模拟辩论流程")
    print("-" * 30)
    
    for i, (speaker, message) in enumerate(test_speeches):
        print(f"\n第 {i+1} 轮发言:")
        
        # 获取当前发言者
        current_speaker = controller.get_current_speaker()
        print(f"推荐发言者: {current_speaker}")
        
        # 记录发言
        controller.record_speech(speaker, message)
        
        # 显示流程状态
        status = controller.get_flow_status()
        print(f"当前状态: {status['current_stage']} 阶段，进度 {status['stage_progress']}")
        print(f"质量分数: {status['stage_metrics']['quality_score']:.3f}")
        print(f"参与平衡: {status['stage_metrics']['participation_balance']:.3f}")
        
        # 检查是否需要推进阶段
        if controller._should_advance_stage():
            print("🔄 准备推进到下一阶段")
            controller.advance_stage()
    
    # 测试发言请求
    print("\n📢 测试发言请求系统")
    print("-" * 30)
    
    controller.request_speaking_turn("正1", "需要反驳对方观点", urgency=4, topic_relevance=0.9)
    controller.request_speaking_turn("反2", "补充论据", urgency=2, topic_relevance=0.7)
    
    next_speaker = controller.get_current_speaker()
    print(f"基于请求的下一位发言者: {next_speaker}")
    
    # 保存数据
    controller.save_flow_data("test_flow_data.json")
    
    print("\n✅ 测试完成")

if __name__ == "__main__":
    main()