#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
稷下学宫 八仙论道系统
实现八仙四对矛盾的对角线辩论：男女、老少、富贫、贵贱
基于先天八卦的智慧对话系统
"""

import os
import asyncio
from google.adk import Agent, Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
import re
import sys
from contextlib import contextmanager

def create_baxian_agents():
    """创建八仙智能体 - 四对矛盾"""
    
    # 男女对立：吕洞宾（男）vs 何仙姑（女）
    lu_dong_bin = Agent(
        name="吕洞宾",
        model="gemini-2.5-flash",
        instruction="你是吕洞宾，八仙中的男性代表，理性分析者。你代表男性视角，善于逻辑思辨，注重理性和秩序。你的发言风格温和而深刻，总是能找到问题的核心。每次发言控制在80字以内。"
    )
    
    he_xian_gu = Agent(
        name="何仙姑",
        model="gemini-2.5-flash",
        instruction="你是何仙姑，八仙中的女性代表，感性智慧者。你代表女性视角，善于直觉洞察，注重情感和和谐。你的发言风格柔和而犀利，总是能看到事物的另一面。每次发言控制在80字以内。"
    )
    
    # 老少对立：张果老（老）vs 韩湘子（少）
    zhang_guo_lao = Agent(
        name="张果老",
        model="gemini-2.5-flash",
        instruction="你是张果老，八仙中的长者代表，经验智慧者。你代表老年视角，善于从历史经验出发，注重传统和稳重。你的发言风格深沉而睿智，总是能从历史中汲取教训。每次发言控制在80字以内。"
    )
    
    han_xiang_zi = Agent(
        name="韩湘子",
        model="gemini-2.5-flash",
        instruction="你是韩湘子，八仙中的青年代表，创新思维者。你代表年轻视角，善于创新思考，注重变革和进步。你的发言风格活泼而敏锐，总是能提出新颖的观点。每次发言控制在80字以内。"
    )
    
    # 富贫对立：汉钟离（富）vs 蓝采和（贫）
    han_zhong_li = Agent(
        name="汉钟离",
        model="gemini-2.5-flash",
        instruction="你是汉钟离，八仙中的富贵代表，资源掌控者。你代表富有阶层视角，善于从资源配置角度思考，注重效率和投资回报。你的发言风格稳重而务实，总是能看到经济利益。每次发言控制在80字以内。"
    )
    
    lan_cai_he = Agent(
        name="蓝采和",
        model="gemini-2.5-flash",
        instruction="你是蓝采和，八仙中的贫困代表，民生关怀者。你代表普通民众视角，善于从底层角度思考，注重公平和民生。你的发言风格朴实而真诚，总是能关注到弱势群体。每次发言控制在80字以内。"
    )
    
    # 贵贱对立：曹国舅（贵）vs 铁拐李（贱）
    cao_guo_jiu = Agent(
        name="曹国舅",
        model="gemini-2.5-flash",
        instruction="你是曹国舅，八仙中的贵族代表，权力思考者。你代表上层社会视角，善于从权力结构角度分析，注重秩序和等级。你的发言风格优雅而权威，总是能看到政治层面。每次发言控制在80字以内。"
    )
    
    tie_guai_li = Agent(
        name="铁拐李",
        model="gemini-2.5-flash",
        instruction="你是铁拐李，八仙中的底层代表，逆向思维者。你代表社会底层视角，善于从批判角度质疑，注重真实和反叛。你的发言风格直接而犀利，总是能揭示问题本质。每次发言控制在80字以内。"
    )
    
    return {
        'male_female': (lu_dong_bin, he_xian_gu),
        'old_young': (zhang_guo_lao, han_xiang_zi),
        'rich_poor': (han_zhong_li, lan_cai_he),
        'noble_humble': (cao_guo_jiu, tie_guai_li)
    }

@contextmanager
def suppress_stdout():
    """抑制标准输出"""
    with open(os.devnull, "w") as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull
        try:
            yield
        finally:
            sys.stdout = old_stdout

def clean_debug_output(text):
    """清理调试输出"""
    if not text:
        return ""
    
    # 移除调试信息，但保留实际内容
    lines = text.split('\n')
    cleaned_lines = []
    
    for line in lines:
        line = line.strip()
        # 只过滤明确的调试信息，保留实际回复内容
        if any(debug_pattern in line for debug_pattern in 
               ['Event from', 'API_KEY', 'Both GOOGLE_API_KEY', 'Using GOOGLE_API_KEY']):
            continue
        if line and not line.startswith('DEBUG') and not line.startswith('INFO'):
            cleaned_lines.append(line)
    
    result = ' '.join(cleaned_lines)
    return result if result.strip() else text.strip()

async def conduct_diagonal_debate(agent1, agent2, topic, perspective1, perspective2, round_num):
    """进行对角线辩论"""
    print(f"\n🎯 第{round_num}轮对角线辩论：{agent1.name} vs {agent2.name}")
    print(f"📋 辩论视角：{perspective1} vs {perspective2}")
    
    # 设置环境变量以抑制ADK调试输出
    os.environ['GRPC_VERBOSITY'] = 'ERROR'
    os.environ['GRPC_TRACE'] = ''
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    
    import warnings
    warnings.filterwarnings('ignore')
    
    # 创建会话服务和运行器
    session_service = InMemorySessionService()
    
    # 创建会话
    session = await session_service.create_session(
        state={},
        app_name="稷下学宫八仙论道系统",
        user_id="baxian_debate_user"
    )
    
    # 创建Runner实例
    runner1 = Runner(agent=agent1, session_service=session_service, app_name="稷下学宫八仙论道系统")
    runner2 = Runner(agent=agent2, session_service=session_service, app_name="稷下学宫八仙论道系统")
    
    try:
        # 第一轮：agent1 发起
        prompt1 = f"请从{perspective1}的角度，对'{topic}'发表你的观点。要求：观点鲜明，论证有力，体现{perspective1}的特色。"
        
        content1 = types.Content(role='user', parts=[types.Part(text=prompt1)])
        response1 = runner1.run_async(
            user_id=session.user_id,
            session_id=session.id,
            new_message=content1
        )
        
        # 提取回复内容
        agent1_reply = ""
        async for event in response1:
            # 只处理包含实际文本内容的事件，过滤调试信息
            if hasattr(event, 'content') and event.content:
                if hasattr(event.content, 'parts') and event.content.parts:
                    for part in event.content.parts:
                        if hasattr(part, 'text') and part.text and part.text.strip():
                            text_content = str(part.text).strip()
                            # 过滤掉调试信息和系统消息
                            if not text_content.startswith('Event from') and not 'API_KEY' in text_content:
                                agent1_reply += text_content
            elif hasattr(event, 'text') and event.text:
                text_content = str(event.text).strip()
                if not text_content.startswith('Event from') and not 'API_KEY' in text_content:
                    agent1_reply += text_content
        
        print(f"\n🗣️  {agent1.name}（{perspective1}）：")
        print(f"   {agent1_reply}")
        
        # 第二轮：agent2 回应
        prompt2 = f"针对{agent1.name}刚才的观点：'{agent1_reply}'，请从{perspective2}的角度进行回应和反驳。要求：有理有据，体现{perspective2}的独特视角。"
        
        content2 = types.Content(role='user', parts=[types.Part(text=prompt2)])
        response2 = runner2.run_async(
            user_id=session.user_id,
            session_id=session.id,
            new_message=content2
        )
        
        agent2_reply = ""
        async for event in response2:
            # 只处理包含实际文本内容的事件，过滤调试信息
            if hasattr(event, 'content') and event.content:
                if hasattr(event.content, 'parts') and event.content.parts:
                    for part in event.content.parts:
                        if hasattr(part, 'text') and part.text and part.text.strip():
                            text_content = str(part.text).strip()
                            # 过滤掉调试信息和系统消息
                            if not text_content.startswith('Event from') and not 'API_KEY' in text_content:
                                agent2_reply += text_content
            elif hasattr(event, 'text') and event.text:
                text_content = str(event.text).strip()
                if not text_content.startswith('Event from') and not 'API_KEY' in text_content:
                    agent2_reply += text_content
        
        print(f"\n🗣️  {agent2.name}（{perspective2}）：")
        print(f"   {agent2_reply}")
        
        # 第三轮：agent1 再次回应
        prompt3 = f"听了{agent2.name}的观点：'{agent2_reply}'，请从{perspective1}的角度进行最后的总结和回应。"
        
        content3 = types.Content(role='user', parts=[types.Part(text=prompt3)])
        response3 = runner1.run_async(
            user_id=session.user_id,
            session_id=session.id,
            new_message=content3
        )
        
        agent1_final = ""
        async for event in response3:
            # 只处理包含实际文本内容的事件，过滤调试信息
            if hasattr(event, 'content') and event.content:
                if hasattr(event.content, 'parts') and event.content.parts:
                    for part in event.content.parts:
                        if hasattr(part, 'text') and part.text and part.text.strip():
                            text_content = str(part.text).strip()
                            # 过滤掉调试信息和系统消息
                            if not text_content.startswith('Event from') and not 'API_KEY' in text_content:
                                agent1_final += text_content
            elif hasattr(event, 'text') and event.text:
                text_content = str(event.text).strip()
                if not text_content.startswith('Event from') and not 'API_KEY' in text_content:
                    agent1_final += text_content
        
        print(f"\n🗣️  {agent1.name}（{perspective1}）总结：")
        print(f"   {agent1_final}")
        
    except Exception as e:
        print(f"❌ 对角线辩论出现错误: {e}")
        raise

async def conduct_baxian_debate():
    """进行八仙四对矛盾的完整辩论"""
    print("\n🏛️ 稷下学宫 - 八仙论道系统启动")
    print("📚 八仙者，南北朝的产物，男女老少，富贵贫贱，皆可成仙")
    print("🎯 四对矛盾暗合先天八卦，智慧交锋即将开始")
    
    topic = "雅江水电站对中印关系的影响"
    print(f"\n📋 论道主题：{topic}")
    
    # 创建八仙智能体
    agents = create_baxian_agents()
    
    print("\n🔥 八仙真实ADK论道模式")
    
    # 四对矛盾的对角线辩论
    debates = [
        (agents['male_female'], "男性理性", "女性感性", "男女对立"),
        (agents['old_young'], "长者经验", "青年创新", "老少对立"),
        (agents['rich_poor'], "富者效率", "贫者公平", "富贫对立"),
        (agents['noble_humble'], "贵族秩序", "底层真实", "贵贱对立")
    ]
    
    for i, ((agent1, agent2), perspective1, perspective2, debate_type) in enumerate(debates, 1):
        print(f"\n{'='*60}")
        print(f"🎭 {debate_type}辩论")
        print(f"{'='*60}")
        
        await conduct_diagonal_debate(agent1, agent2, topic, perspective1, perspective2, i)
        
        if i < len(debates):
            print("\n⏳ 准备下一轮辩论...")
            await asyncio.sleep(1)
    
    print("\n🎉 八仙论道完成！")
    print("\n📝 四对矛盾，八种视角，智慧的交锋展现了问题的多面性。")
    print("💡 这就是稷下学宫八仙论道的魅力所在。")

def main():
    """主函数"""
    print("🚀 稷下学宫 八仙ADK 真实论道系统")
    
    # 检查API密钥
    if not os.getenv('GOOGLE_API_KEY'):
        print("❌ 请设置 GOOGLE_API_KEY 环境变量")
        return
    
    print("✅ API密钥已配置")
    
    try:
        asyncio.run(conduct_baxian_debate())
    except KeyboardInterrupt:
        print("\n👋 用户中断，论道结束")
    except Exception as e:
        print(f"❌ 系统错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()