#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
辩论主持人智能体
Debate Master Agent
"""

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

from jixia_academy.core.memory_bank.interface import MemoryBankInterface


class DebateMaster:
    """辩论主持人"""
    
    def __init__(self, memory_bank: MemoryBankInterface):
        self.memory_bank = memory_bank
        self.initialized = False
        
    async def initialize(self):
        """初始化主持人"""
        if self.initialized:
            return
            
        print("🎭 初始化辩论主持人...")
        self.initialized = True
    
    async def close(self):
        """关闭资源"""
        self.initialized = False
    
    async def open_debate(
        self,
        topic: str,
        participants: List[str]
    ) -> str:
        """开场白"""
        
        # 根据话题和参与者生成开场白
        opening_templates = [
            f"各位仙友，今日我们齐聚稷下学宫，共商"{topic}"这一重要议题。",
            f"让我们以{', '.join(participants)}的智慧，共同探讨"{topic}"的深层含义。",
            f"今日辩论的主题是"{topic}"，请各位仙人畅所欲言，各抒己见。"
        ]
        
        # 根据参与者数量选择不同的开场白
        if len(participants) <= 3:
            opening = opening_templates[1]
        else:
            opening = opening_templates[2]
        
        return opening
    
    async def close_debate(
        self,
        topic: str,
        participants: List[str],
        summary: Dict[str, Any]
    ) -> str:
        """结束语"""
        
        # 生成总结性结束语
        closing_parts = []
        
        # 开场
        closing_parts.append(f"今日关于"{topic}"的辩论到此结束。")
        
        # 参与者总结
        if len(participants) > 1:
            closing_parts.append(f"感谢{', '.join(participants)}的精彩发言。")
        
        # 观点总结
        consensus = summary.get("consensus", [])
        if consensus:
            closing_parts.append(f"我们达成了以下共识：{'; '.join(consensus)}")
        
        # 分歧总结
        disagreements = summary.get("disagreements", [])
        if disagreements:
            closing_parts.append(f"存在的分歧包括：{'; '.join(disagreements)}")
        
        # 结束语
        closing_parts.append("让我们带着今天的智慧，继续前行。")
        
        return " ".join(closing_parts)
    
    async def summarize_debate(self, debate_id: str) -> Dict[str, Any]:
        """总结辩论"""
        
        # 获取辩论历史
        history = await self.memory_bank.get_debate_history(debate_id)
        
        # 分析辩论内容
        analysis = await self._analyze_debate_content(history)
        
        # 生成总结
        summary = {
            "total_messages": len(history),
            "participants": list(set([h.get("speaker", "") for h in history])),
            "consensus": analysis.get("consensus", []),
            "disagreements": analysis.get("disagreements", []),
            "key_points": analysis.get("key_points", []),
            "timestamp": datetime.now().isoformat()
        }
        
        return summary
    
    async def _analyze_debate_content(
        self,
        history: List[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """分析辩论内容"""
        
        if not history:
            return {
                "consensus": [],
                "disagreements": [],
                "key_points": []
            }
        
        # 提取所有消息内容
        all_messages = [h.get("message", "") for h in history]
        content = " ".join(all_messages)
        
        # 简化版分析
        key_words = ["风险", "机会", "收益", "损失", "策略", "建议"]
        key_points = [kw for kw in key_words if kw in content]
        
        # 基于内容长度和参与者数量估算共识
        participants = list(set([h.get("speaker", "") for h in history]))
        
        consensus = []
        disagreements = []
        
        # 简化版共识识别
        if "风险" in content and "机会" in content:
            consensus.append("同时关注风险和机会")
        
        if len(participants) > 2:
            consensus.append("多方参与讨论")
        
        # 简化版分歧识别
        if "但是" in content or "然而" in content:
            disagreements.append("存在不同观点")
        
        return {
            "consensus": consensus,
            "disagreements": disagreements,
            "key_points": key_points
        }
    
    async def moderate_dispute(
        self,
        dispute: str,
        participants: List[str]
    ) -> str:
        """调解争议"""
        
        # 生成调解建议
        moderation_templates = [
            f"各位仙友，关于"{dispute}"，让我们回归理性讨论。",
            f"我理解{', '.join(participants)}的不同观点，让我们寻找共同点。",
            f"争议"{dispute}"体现了问题的复杂性，我们需要更深入的分析。"
        ]
        
        # 根据争议类型选择调解方式
        return moderation_templates[0]
    
    def get_info(self) -> Dict[str, Any]:
        """获取主持人信息"""
        return {
            "role": "辩论主持人",
            "responsibilities": [
                "开场和结束辩论",
                "总结辩论观点",
                "调解争议",
                "维持辩论秩序"
            ],
            "initialized": self.initialized
        }


async def test_debate_master():
    """测试辩论主持人"""
    from jixia_academy.core.memory_bank.factory import get_memory_backend
    
    memory_bank = get_memory_backend()
    await memory_bank.initialize()
    
    master = DebateMaster(memory_bank=memory_bank)
    await master.initialize()
    
    # 测试开场白
    opening = await master.open_debate(
        topic="人工智能对投资的影响",
        participants=["铁拐李", "吕洞宾", "何仙姑"]
    )
    print(f"\n🎯 开场白: {opening}")
    
    # 测试结束语
    closing = await master.close_debate(
        topic="人工智能对投资的影响",
        participants=["铁拐李", "吕洞宾", "何仙姑"],
        summary={
            "consensus": ["关注技术风险", "寻找投资机会"],
            "disagreements": ["对发展速度的看法不同"]
        }
    )
    print(f"\n🎯 结束语: {closing}")
    
    await master.close()
    await memory_bank.close()


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