#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
八仙论道辩论协调器
Baxian Debate Coordinator
"""

import asyncio
import logging
from typing import List, Dict, Any, Optional
from datetime import datetime

from jixia_academy.core.memory_bank.interface import MemoryBankInterface
from jixia_academy.agents.baxian.baxian_agent import BaxianAgent
from jixia_academy.agents.host.debate_master import DebateMaster


class BaxianCoordinator:
    """八仙论道辩论协调器"""
    
    def __init__(self, memory_bank: MemoryBankInterface):
        self.memory_bank = memory_bank
        self.agents: Dict[str, BaxianAgent] = {}
        self.debate_master = DebateMaster(memory_bank=memory_bank)
        self.initialized = False
        
    async def initialize(self):
        """初始化八仙辩论系统"""
        if self.initialized:
            return
            
        print("🎭 初始化八仙辩论协调器...")
        
        # 初始化八仙角色
        baxian_roles = {
            "铁拐李": {
                "personality": "逆向思维专家",
                "expertise": ["批判性思维", "风险识别", "逆向投资"],
                "style": "直接犀利，善于质疑"
            },
            "吕洞宾": {
                "personality": "理性分析者",
                "expertise": ["逻辑分析", "平衡观点", "理性决策"],
                "style": "温和深刻，逻辑清晰"
            },
            "何仙姑": {
                "personality": "风险控制专家",
                "expertise": ["风险管理", "谨慎决策", "风险预警"],
                "style": "谨慎细致，注重安全"
            },
            "张果老": {
                "personality": "历史智慧者",
                "expertise": ["历史规律", "长期视角", "经验总结"],
                "style": "沉稳博学，引经据典"
            },
            "蓝采和": {
                "personality": "创新思维者",
                "expertise": ["创新视角", "非传统方法", "独特见解"],
                "style": "活泼新颖，创意无限"
            },
            "汉钟离": {
                "personality": "平衡协调者",
                "expertise": ["综合观点", "和谐统一", "矛盾化解"],
                "style": "平和包容，寻求共识"
            },
            "韩湘子": {
                "personality": "艺术感知者",
                "expertise": ["美学感知", "深层含义", "情感洞察"],
                "style": "优雅感性，触动人心"
            },
            "曹国舅": {
                "personality": "实务执行者",
                "expertise": ["实际操作", "具体细节", "可行方案"],
                "style": "务实严谨，建设性强"
            }
        }
        
        # 创建八仙智能体
        for name, config in baxian_roles.items():
            self.agents[name] = BaxianAgent(
                name=name,
                personality=config["personality"],
                expertise=config["expertise"],
                style=config["style"],
                memory_bank=self.memory_bank
            )
            await self.agents[name].initialize()
        
        await self.debate_master.initialize()
        self.initialized = True
        print("✅ 八仙辩论协调器初始化完成")
    
    async def close(self):
        """关闭资源"""
        for agent in self.agents.values():
            await agent.close()
        await self.debate_master.close()
        self.initialized = False
    
    async def conduct_debate(
        self,
        topic: str,
        participants: List[str],
        rounds: int,
        debate_id: str
    ):
        """进行八仙论道辩论"""
        if not self.initialized:
            await self.initialize()
        
        # 验证参与者
        valid_participants = [p for p in participants if p in self.agents]
        if len(valid_participants) < 2:
            raise ValueError("需要至少2位有效参与者")
        
        print(f"🎯 有效参与者: {', '.join(valid_participants)}")
        
        # 开始辩论
        await self._start_debate(topic, valid_participants, debate_id)
        
        # 进行多轮辩论
        for round_num in range(rounds):
            print(f"\n🔄 第 {round_num + 1} 轮辩论:")
            await self._conduct_round(
                topic=topic,
                participants=valid_participants,
                round_num=round_num + 1,
                debate_id=debate_id
            )
        
        # 结束辩论
        await self._end_debate(topic, valid_participants, debate_id)
    
    async def _start_debate(
        self,
        topic: str,
        participants: List[str],
        debate_id: str
    ):
        """开始辩论"""
        # 主持人开场白
        opening = await self.debate_master.open_debate(topic, participants)
        print(f"\n📢 主持人开场: {opening}")
        
        # 记录开场白
        await self.memory_bank.add_debate_message(
            debate_id=debate_id,
            speaker="主持人",
            message=opening,
            round_num=0
        )
    
    async def _conduct_round(
        self,
        topic: str,
        participants: List[str],
        round_num: int,
        debate_id: str
    ):
        """进行一轮辩论"""
        # 获取上一轮的历史
        history = await self.memory_bank.get_debate_history(debate_id)
        
        # 每位仙人发言
        for participant in participants:
            agent = self.agents[participant]
            
            # 生成观点
            response = await agent.generate_viewpoint(
                topic=topic,
                history=history,
                round_num=round_num
            )
            
            print(f"\n🗣️ {participant}: {response}")
            
            # 记录发言
            await self.memory_bank.add_debate_message(
                debate_id=debate_id,
                speaker=participant,
                message=response,
                round_num=round_num
            )
            
            # 短暂停顿
            await asyncio.sleep(0.5)
    
    async def _end_debate(
        self,
        topic: str,
        participants: List[str],
        debate_id: str
    ):
        """结束辩论"""
        # 获取完整辩论历史
        full_history = await self.memory_bank.get_debate_history(debate_id)
        
        # 生成总结
        summary = await self.debate_master.summarize_debate(debate_id)
        
        # 主持人结束语
        closing = await self.debate_master.close_debate(topic, participants, summary)
        print(f"\n📢 主持人总结: {closing}")
        
        # 记录总结
        await self.memory_bank.add_debate_message(
            debate_id=debate_id,
            speaker="主持人",
            message=closing,
            round_num=-1
        )
        
        # 保存辩论结果
        await self.memory_bank.save_debate_result(
            debate_id=debate_id,
            summary=summary,
            participants=participants
        )


async def test_baxian_coordinator():
    """测试八仙协调器"""
    from jixia_academy.core.memory_bank.factory import get_memory_backend
    
    memory_bank = get_memory_backend()
    await memory_bank.initialize()
    
    coordinator = BaxianCoordinator(memory_bank=memory_bank)
    await coordinator.initialize()
    
    # 测试辩论
    await coordinator.conduct_debate(
        topic="人工智能对投资的影响",
        participants=["铁拐李", "吕洞宾", "何仙姑"],
        rounds=2,
        debate_id="test_debate_001"
    )
    
    await coordinator.close()
    await memory_bank.close()


if __name__ == "__main__":
    asyncio.run(test_baxian_coordinator())