#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
稷下学宫AI辩论系统 - 核心引擎
Jixia Academy AI Debate System - Core Engine
"""

import asyncio
import logging
from typing import List, Dict, Any, Optional
from pathlib import Path

from jixia_academy.core.memory_bank.factory import get_memory_backend
from jixia_academy.agents.baxian.baxian_coordinator import BaxianCoordinator
from jixia_academy.agents.host.debate_master import DebateMaster


class JixiaAcademy:
    """稷下学宫AI辩论系统主类"""
    
    def __init__(self):
        self.memory_bank = None
        self.baxian_coordinator = None
        self.debate_master = None
        self.initialized = False
        
    async def initialize(self):
        """初始化系统"""
        if self.initialized:
            return
            
        print("🚀 初始化稷下学宫AI辩论系统...")
        
        # 初始化记忆银行
        self.memory_bank = get_memory_backend()
        await self.memory_bank.initialize()
        
        # 初始化八仙协调器
        self.baxian_coordinator = BaxianCoordinator(memory_bank=self.memory_bank)
        await self.baxian_coordinator.initialize()
        
        # 初始化辩论主持人
        self.debate_master = DebateMaster(memory_bank=self.memory_bank)
        await self.debate_master.initialize()
        
        self.initialized = True
        print("✅ 稷下学宫AI辩论系统初始化完成")
    
    async def close(self):
        """关闭系统资源"""
        if self.memory_bank:
            await self.memory_bank.close()
        if self.baxian_coordinator:
            await self.baxian_coordinator.close()
        if self.debate_master:
            await self.debate_master.close()
        
        self.initialized = False
        print("🛑 系统已关闭")
    
    async def run_baxian_debate(
        self,
        topic: str,
        rounds: int = 3,
        participants: List[str] = None
    ):
        """运行八仙论道辩论"""
        if not self.initialized:
            await self.initialize()
        
        if participants is None:
            participants = [
                "铁拐李", "吕洞宾", "何仙姑", "张果老",
                "蓝采和", "汉钟离", "韩湘子", "曹国舅"
            ]
        
        print(f"\n🏛️ 稷下学宫八仙论道")
        print(f"📋 辩论主题: {topic}")
        print(f"🎭 参与八仙: {', '.join(participants)}")
        print(f"🔄 辩论轮数: {rounds}")
        print("=" * 50)
        
        # 创建辩论会话
        debate_id = await self.memory_bank.create_debate_session(
            topic=topic,
            participants=participants,
            debate_type="baxian"
        )
        
        # 运行辩论
        await self.baxian_coordinator.conduct_debate(
            topic=topic,
            participants=participants,
            rounds=rounds,
            debate_id=debate_id
        )
        
        # 生成辩论总结
        summary = await self.debate_master.summarize_debate(debate_id)
        print(f"\n📊 辩论总结: {summary}")
    
    async def run_memory_enhanced_debate(
        self,
        topic: str,
        engine: str = "adk"
    ):
        """运行记忆增强辩论"""
        if not self.initialized:
            await self.initialize()
        
        print(f"\n🧠 记忆增强辩论")
        print(f"📋 主题: {topic}")
        print(f"⚙️ 引擎: {engine}")
        print("=" * 50)
        
        # 获取历史记忆
        historical_context = await self.memory_bank.get_related_memories(topic)
        
        # 创建增强辩论会话
        debate_id = await self.memory_bank.create_debate_session(
            topic=topic,
            participants=["记忆增强AI"],
            debate_type="memory_enhanced",
            context=historical_context
        )
        
        # 运行辩论（根据引擎类型）
        if engine == "adk":
            await self._run_adk_memory_debate(topic, debate_id)
        elif engine == "swarm":
            await self._run_swarm_memory_debate(topic, debate_id)
    
    async def _run_adk_memory_debate(self, topic: str, debate_id: str):
        """运行ADK记忆增强辩论"""
        from jixia_academy.integrations.adk.adk_client import ADKClient
        
        client = ADKClient(memory_bank=self.memory_bank)
        await client.run_debate(topic, debate_id)
    
    async def _run_swarm_memory_debate(self, topic: str, debate_id: str):
        """运行Swarm记忆增强辩论"""
        from jixia_academy.integrations.adk.swarm_client import SwarmClient
        
        client = SwarmClient(memory_bank=self.memory_bank)
        await client.run_debate(topic, debate_id)
    
    async def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        status = {
            "initialized": self.initialized,
            "memory_bank": "connected" if self.memory_bank else "disconnected",
            "baxian_coordinator": "ready" if self.baxian_coordinator else "not_ready",
            "debate_master": "ready" if self.debate_master else "not_ready"
        }
        
        if self.memory_bank:
            stats = await self.memory_bank.get_stats()
            status["memory_stats"] = stats
        
        return status


async def main():
    """测试主函数"""
    academy = JixiaAcademy()
    await academy.initialize()
    
    # 获取系统状态
    status = await academy.get_system_status()
    print("系统状态:", status)
    
    await academy.close()


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