#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
太公心易 - 起承转合辩论系统
基于先天八卦的八仙辩论架构
"""

import asyncio
import json
from datetime import datetime
from typing import Dict, List, Any, Optional
from dataclasses import dataclass
from enum import Enum
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from enhanced_priority_algorithm import EnhancedPriorityAlgorithm, SpeechAnalysis

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

@dataclass
class Speaker:
    """发言者数据类"""
    name: str
    role: str
    team: str  # "positive" or "negative"
    bagua_position: Optional[int] = None  # 八卦位置（0-7）

@dataclass
class DebateContext:
    """辩论上下文"""
    current_stage: DebateStage
    stage_progress: int
    total_handoffs: int
    current_speaker: Optional[str] = None
    last_message: Optional[str] = None
    debate_history: List[Dict] = None
    last_priority_analysis: Optional[Dict[str, Any]] = None

class QiChengZhuanHeDebateSystem:
    """起承转合辩论系统"""
    
    def __init__(self):
        # 八仙配置（按先天八卦顺序）
        self.baxian_speakers = {
            "吕洞宾": Speaker("吕洞宾", "剑仙投资顾问", "neutral", 0),  # 乾
            "何仙姑": Speaker("何仙姑", "慈悲风控专家", "neutral", 1),  # 兑
            "铁拐李": Speaker("铁拐李", "逆向思维专家", "neutral", 2),  # 离
            "汉钟离": Speaker("汉钟离", "平衡协调者", "neutral", 3),    # 震
            "蓝采和": Speaker("蓝采和", "创新思维者", "neutral", 4),    # 巽
            "张果老": Speaker("张果老", "历史智慧者", "neutral", 5),    # 坎
            "韩湘子": Speaker("韩湘子", "艺术感知者", "neutral", 6),    # 艮
            "曹国舅": Speaker("曹国舅", "实务执行者", "neutral", 7)     # 坤
        }
        
        # 雁阵队伍配置
        self.goose_formation = {
            "positive": ["正1", "正2", "正3", "正4"],
            "negative": ["反1", "反2", "反3", "反4"]
        }
        
        # 辩论状态
        self.context = DebateContext(
            current_stage=DebateStage.QI,
            stage_progress=0,
            total_handoffs=0,
            debate_history=[]
        )
        
        # 阶段配置
        self.stage_configs = {
            DebateStage.QI: {
                "duration": "8-10分钟",
                "max_progress": 8,  # 八仙轮流发言
                "description": "八仙按先天八卦顺序阐述观点"
            },
            DebateStage.CHENG: {
                "duration": "8-10分钟", 
                "max_progress": 8,  # 正反各4人
                "description": "雁阵式承接，总体阐述+讥讽"
            },
            DebateStage.ZHUAN: {
                "duration": "12-15分钟",
                "max_progress": 36,  # 36次handoff
                "description": "自由辩论，优先级算法决定发言"
            },
            DebateStage.HE: {
                "duration": "8-10分钟",
                "max_progress": 8,  # 交替总结
                "description": "交替总结，最终论证"
            }
        }
        
        # 增强版优先级算法
        self.priority_algorithm = EnhancedPriorityAlgorithm()
        
        # 记忆系统
        self.memory_system = DebateMemorySystem()
    
    def get_current_speaker(self) -> str:
        """获取当前发言者"""
        stage = self.context.current_stage
        progress = self.context.stage_progress
        
        if stage == DebateStage.QI:
            return self._get_bagua_speaker(progress)
        elif stage == DebateStage.CHENG:
            return self._get_goose_formation_speaker(progress)
        elif stage == DebateStage.ZHUAN:
            return self._get_priority_speaker()
        elif stage == DebateStage.HE:
            return self._get_alternating_speaker(progress)
        
        return "未知发言者"
    
    def _get_bagua_speaker(self, progress: int) -> str:
        """获取八卦顺序发言者"""
        bagua_sequence = ["吕洞宾", "何仙姑", "铁拐李", "汉钟离", "蓝采和", "张果老", "韩湘子", "曹国舅"]
        return bagua_sequence[progress % 8]
    
    def _get_goose_formation_speaker(self, progress: int) -> str:
        """获取雁阵发言者"""
        if progress < 4:
            # 正方雁阵
            return self.goose_formation["positive"][progress]
        else:
            # 反方雁阵
            return self.goose_formation["negative"][progress - 4]
    
    def _get_priority_speaker(self) -> str:
        """获取优先级发言者（转阶段）"""
        available_speakers = ["正1", "正2", "正3", "正4", "反1", "反2", "反3", "反4"]
        
        # 构建上下文
        context = {
            "current_stage": self.context.current_stage.value,
            "stage_progress": self.context.stage_progress,
            "max_progress": self.stage_configs[self.context.current_stage]["max_progress"],
            "time_remaining": max(0.1, 1.0 - (self.context.stage_progress / self.stage_configs[self.context.current_stage]["max_progress"])),
            "topic_keywords": ["投资", "AI", "风险", "收益"],  # 可配置
            "positive_team_score": 0.5,  # 可动态计算
            "negative_team_score": 0.5,  # 可动态计算
            "positive_recent_speeches": len([h for h in self.context.debate_history[-10:] if "正" in h.get("speaker", "")]),
            "negative_recent_speeches": len([h for h in self.context.debate_history[-10:] if "反" in h.get("speaker", "")])
        }
        
        # 获取最近发言历史
        recent_speeches = self.context.debate_history[-10:] if self.context.debate_history else []
        
        next_speaker, score, analysis = self.priority_algorithm.get_next_speaker(
            available_speakers, context, recent_speeches
        )
        
        # 记录分析结果
        self.context.last_priority_analysis = {
            "recommended_speaker": next_speaker,
            "priority_score": score,
            "analysis": analysis,
            "timestamp": datetime.now().isoformat()
        }
        
        return next_speaker
    
    def _get_alternating_speaker(self, progress: int) -> str:
        """获取交替总结发言者"""
        alternating_sequence = ["反1", "正1", "反2", "正2", "反3", "正3", "反4", "正4"]
        return alternating_sequence[progress % 8]
    
    def advance_stage(self):
        """推进辩论阶段"""
        current_config = self.stage_configs[self.context.current_stage]
        
        if self.context.stage_progress >= current_config["max_progress"] - 1:
            # 当前阶段完成，进入下一阶段
            self._transition_to_next_stage()
        else:
            # 当前阶段继续
            self.context.stage_progress += 1
    
    def _transition_to_next_stage(self):
        """转换到下一阶段"""
        stage_transitions = {
            DebateStage.QI: DebateStage.CHENG,
            DebateStage.CHENG: DebateStage.ZHUAN,
            DebateStage.ZHUAN: DebateStage.HE,
            DebateStage.HE: None  # 辩论结束
        }
        
        next_stage = stage_transitions[self.context.current_stage]
        if next_stage:
            self.context.current_stage = next_stage
            self.context.stage_progress = 0
            print(f"🎭 辩论进入{next_stage.value}阶段")
        else:
            print("🎉 辩论结束！")
    
    def record_speech(self, speaker: str, message: str):
        """记录发言"""
        speech_record = {
            "timestamp": datetime.now().isoformat(),
            "stage": self.context.current_stage.value,
            "stage_progress": self.context.stage_progress,
            "speaker": speaker,
            "message": message,
            "total_handoffs": self.context.total_handoffs
        }
        
        self.context.debate_history.append(speech_record)
        self.context.last_message = message
        self.context.current_speaker = speaker
        
        # 更新记忆系统
        self.memory_system.store_speech(speaker, message, self.context)
        
        # 如果是转阶段，增加handoff计数
        if self.context.current_stage == DebateStage.ZHUAN:
            self.context.total_handoffs += 1
    
    def get_stage_info(self) -> Dict[str, Any]:
        """获取当前阶段信息"""
        stage = self.context.current_stage
        config = self.stage_configs[stage]
        
        return {
            "current_stage": stage.value,
            "stage_progress": self.context.stage_progress,
            "max_progress": config["max_progress"],
            "description": config["description"],
            "current_speaker": self.get_current_speaker(),
            "total_handoffs": self.context.total_handoffs
        }
    
    def save_debate_state(self, filename: str = "debate_state.json"):
        """保存辩论状态"""
        state_data = {
            "context": {
                "current_stage": self.context.current_stage.value,
                "stage_progress": self.context.stage_progress,
                "total_handoffs": self.context.total_handoffs,
                "current_speaker": self.context.current_speaker,
                "last_message": self.context.last_message
            },
            "debate_history": self.context.debate_history,
            "memory_data": self.memory_system.get_memory_data()
        }
        
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(state_data, f, ensure_ascii=False, indent=2)
        
        print(f"💾 辩论状态已保存到 {filename}")

# 旧的PriorityAlgorithm类已被EnhancedPriorityAlgorithm替换

class DebateMemorySystem:
    """辩论记忆系统"""
    
    def __init__(self):
        self.speaker_memories = {}
        self.debate_memories = []
    
    def store_speech(self, speaker: str, message: str, context: DebateContext):
        """存储发言记忆"""
        if speaker not in self.speaker_memories:
            self.speaker_memories[speaker] = []
        
        memory_entry = {
            "timestamp": datetime.now().isoformat(),
            "stage": context.current_stage.value,
            "message": message,
            "context": {
                "stage_progress": context.stage_progress,
                "total_handoffs": context.total_handoffs
            }
        }
        
        self.speaker_memories[speaker].append(memory_entry)
        self.debate_memories.append(memory_entry)
    
    def get_speaker_memory(self, speaker: str, limit: int = 5) -> List[Dict]:
        """获取发言者记忆"""
        if speaker in self.speaker_memories:
            return self.speaker_memories[speaker][-limit:]
        return []
    
    def get_memory_data(self) -> Dict[str, Any]:
        """获取记忆数据"""
        return {
            "speaker_memories": self.speaker_memories,
            "debate_memories": self.debate_memories
        }

def main():
    """主函数 - 测试起承转合辩论系统"""
    print("🚀 太公心易 - 起承转合辩论系统")
    print("=" * 60)
    
    # 创建辩论系统
    debate_system = QiChengZhuanHeDebateSystem()
    
    # 测试各阶段
    test_messages = [
        "起：八仙按先天八卦顺序阐述观点",
        "承：雁阵式承接，总体阐述+讥讽", 
        "转：自由辩论，36次handoff",
        "合：交替总结，最终论证"
    ]
    
    for i, message in enumerate(test_messages):
        stage_info = debate_system.get_stage_info()
        current_speaker = debate_system.get_current_speaker()
        
        print(f"\n🎭 当前阶段: {stage_info['current_stage']}")
        print(f"📊 进度: {stage_info['stage_progress'] + 1}/{stage_info['max_progress']}")
        print(f"🗣️ 发言者: {current_speaker}")
        print(f"💬 消息: {message}")
        
        # 记录发言
        debate_system.record_speech(current_speaker, message)
        
        # 推进阶段
        debate_system.advance_stage()
    
    # 保存状态
    debate_system.save_debate_state()
    
    print("\n✅ 起承转合辩论系统测试完成！")

if __name__ == "__main__":
    main()

