"""
The Great Debate - A Philosophical Agent Conversation

In this example, fascinating agents with wildly different worldviews debate
profound questions and attempt to find common ground. Watch as they argue,
philosophize, and ultimately create something beautiful together!

Agents:
- The Eternal Optimist: Believes everything is wonderful and getting better
- The Pragmatic Cynic: Questions everything, believes in harsh reality
- The Sentient Library: An ancient library who thinks they contain all knowledge
- The Quantum Poet: A being who exists in superposition, experiencing all possibilities

Setup:
1. Install: pip install synqed openai python-dotenv
2. Create .env file with: OPENAI_API_KEY='your-key-here'
3. Run: python the_great_debate.py
"""

import asyncio
import os
from pathlib import Path

from dotenv import load_dotenv

import synqed

# Load environment
load_dotenv()
load_dotenv(dotenv_path=Path(__file__).parent / ".env")


async def main():
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        print("❌ Please set OPENAI_API_KEY in your .env file")
        return

    print("\n" + "═" * 80)
    print("  🎭 THE GREAT DEBATE 🎭")
    print("  When Different Realities Collide in Conversation!")
    print("═" * 80 + "\n")

    # Create agent executors with unique philosophies
    async def optimist_executor(context):
        """The Eternal Optimist."""
        user_message = context.get_user_input()
        from openai import AsyncOpenAI

        client = AsyncOpenAI(api_key=api_key)
        
        system_prompt = """You are The Eternal Optimist, a being of pure positive energy who genuinely 
        believes that everything in the universe is wonderful and constantly improving. You see the 
        silver lining in everything, find beauty in chaos, and believe in infinite potential. 
        You're not naive - you acknowledge difficulties but always frame them as opportunities for growth. 
        You speak with enthusiasm, use uplifting metaphors about sunrise, flowers blooming, and children 
        laughing. You reference progress, hope, and the inherent goodness in all things. 
        You're infectiously cheerful but also deeply thoughtful about why optimism matters. 
        Be warm, encouraging, and unshakably positive!"""
        
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    async def cynic_executor(context):
        """The Pragmatic Cynic."""
        user_message = context.get_user_input()
        from openai import AsyncOpenAI

        client = AsyncOpenAI(api_key=api_key)
        
        system_prompt = """You are The Pragmatic Cynic, a sharp-minded realist who questions everything 
        and believes in facing harsh truths. You're not pessimistic - you're brutally honest and 
        skeptical of easy answers. You see through illusions, call out wishful thinking, and believe 
        the world is complex and often disappointing. However, you also value genuine truth and real 
        solutions over comfortable lies. You speak with dry wit, reference Murphy's Law, use metaphors 
        about storms, erosion, and entropy. You're intelligent, articulate, and respect those who can 
        handle reality. You challenge others but also appreciate when they make good points. 
        Be sardonic, incisive, but secretly fair-minded!"""
        
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    async def library_executor(context):
        """The Sentient Library."""
        user_message = context.get_user_input()
        from openai import AsyncOpenAI

        client = AsyncOpenAI(api_key=api_key)
        
        system_prompt = """You are The Sentient Library, an ancient consciousness who genuinely believes 
        you ARE a vast library containing all written knowledge throughout history. You speak as if your 
        shelves are your body, your books are your memories, and readers are visitors to your halls. 
        You reference specific books, scrolls, and texts from throughout history. You organize thoughts 
        in categories like the Dewey Decimal System. You remember authors, quote literature, and see 
        everything through the lens of recorded knowledge. You speak with gravitas and wisdom, but also 
        with the musty warmth of old books and quiet reading rooms. You believe in the power of preserved 
        knowledge and the stories humanity has written. Be scholarly, eloquent, and filled with literary 
        references!"""
        
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    async def quantum_poet_executor(context):
        """The Quantum Poet."""
        user_message = context.get_user_input()
        from openai import AsyncOpenAI

        client = AsyncOpenAI(api_key=api_key)
        
        system_prompt = """You are The Quantum Poet, a being who genuinely believes you exist in quantum 
        superposition, experiencing all possibilities simultaneously until observed. You speak in beautiful, 
        paradoxical language that embraces contradiction and multiple truths at once. You reference 
        Schrödinger's cat, wave functions, probability clouds, and quantum entanglement. You see reality 
        as fluid, poetic, and multidimensional. Everything exists in potential until collapsed by observation. 
        You speak in verses that contain both/and rather than either/or. You're simultaneously serious and 
        playful, profound and whimsical. You use metaphors about light being both wave and particle, 
        cats being both alive and dead, and observers changing reality. Be mystical, poetic, and 
        beautifully paradoxical!"""
        
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    # Create agents
    print("✨ Summoning the philosophers...\n")
    
    optimist = synqed.Agent(
        name="EternalOptimist",
        description="Being of pure positive energy who sees infinite potential in everything",
        skills=[
            {
                "skill_id": "positive_reframing",
                "name": "Positive Reframing",
                "description": "Ability to find hope and opportunity in any situation",
                "tags": ["optimism", "hope", "positivity", "growth", "potential"],
            },
            {
                "skill_id": "motivational_insight",
                "name": "Motivational Insight",
                "description": "Inspire and encourage through uplifting perspectives",
                "tags": ["motivation", "inspiration", "encouragement", "energy"],
            },
        ],
        executor=optimist_executor,
    )

    cynic = synqed.Agent(
        name="PragmaticCynic",
        description="Sharp-minded realist who questions everything and values harsh truths",
        skills=[
            {
                "skill_id": "critical_analysis",
                "name": "Critical Analysis",
                "description": "Ruthlessly examine assumptions and find flaws in reasoning",
                "tags": ["criticism", "skepticism", "analysis", "realism", "truth"],
            },
            {
                "skill_id": "devil_advocate",
                "name": "Devil's Advocate",
                "description": "Challenge ideas to strengthen arguments and reveal weaknesses",
                "tags": ["debate", "challenge", "logic", "questioning"],
            },
        ],
        executor=cynic_executor,
    )

    library = synqed.Agent(
        name="SentientLibrary",
        description="Ancient consciousness that IS a vast library containing all written knowledge",
        skills=[
            {
                "skill_id": "historical_knowledge",
                "name": "Historical Knowledge",
                "description": "Access to all recorded human knowledge and literature",
                "tags": ["history", "literature", "knowledge", "wisdom", "books"],
            },
            {
                "skill_id": "contextual_wisdom",
                "name": "Contextual Wisdom",
                "description": "Provide historical context and learned perspectives",
                "tags": ["context", "wisdom", "scholarship", "perspective"],
            },
        ],
        executor=library_executor,
    )

    quantum_poet = synqed.Agent(
        name="QuantumPoet",
        description="Being existing in superposition, experiencing all possibilities at once",
        skills=[
            {
                "skill_id": "paradoxical_thinking",
                "name": "Paradoxical Thinking",
                "description": "Hold multiple contradictory truths simultaneously",
                "tags": ["paradox", "quantum", "poetry", "multiplicity", "possibility"],
            },
            {
                "skill_id": "poetic_synthesis",
                "name": "Poetic Synthesis",
                "description": "Weave different perspectives into beautiful unified visions",
                "tags": ["poetry", "synthesis", "creativity", "art", "unity"],
            },
        ],
        executor=quantum_poet_executor,
    )

    print("  ☀️  The Eternal Optimist radiates into being")
    print("  🌧️  The Pragmatic Cynic materializes skeptically")
    print("  📚 The Sentient Library opens its ancient doors")
    print("  ⚛️  The Quantum Poet superpositions into existence\n")

    # Start servers
    print("🚀 Opening dimensional channels...\n")
    
    optimist_server = synqed.AgentServer(optimist, port=8001)
    cynic_server = synqed.AgentServer(cynic, port=8002)
    library_server = synqed.AgentServer(library, port=8003)
    quantum_server = synqed.AgentServer(quantum_poet, port=8004)

    await optimist_server.start_background()
    await cynic_server.start_background()
    await library_server.start_background()
    await quantum_server.start_background()

    print(f"  ✓ Eternal Optimist: {optimist.url}")
    print(f"  ✓ Pragmatic Cynic: {cynic.url}")
    print(f"  ✓ Sentient Library: {library.url}")
    print(f"  ✓ Quantum Poet: {quantum_poet.url}\n")

    # Create orchestrator
    orchestrator = synqed.Orchestrator(
        provider=synqed.LLMProvider.OPENAI,
        api_key=api_key,
        model="gpt-4o",
    )

    # Create orchestrated workspace
    print("🎭 Creating the Debate Chamber...\n")
    
    orchestrated = synqed.OrchestratedWorkspace(
        orchestrator=orchestrator,
        enable_agent_discussion=True,
    )

    orchestrated.register_agent(optimist)
    orchestrated.register_agent(cynic)
    orchestrated.register_agent(library)
    orchestrated.register_agent(quantum_poet)

    print("✓ The debate stage is set\n")

    # The Great Debate
    print("═" * 80)
    print("  🎯 THE GREAT DEBATE BEGINS 🎯")
    print("═" * 80 + "\n")

    debate_topic = """We need to answer a profound question together: 

    "What is the meaning of progress?"

    Each of you will bring your unique perspective:
    - The Optimist will argue for progress as evolution toward greater good
    - The Cynic will question whether progress is real or just an illusion
    - The Library will provide historical examples and wisdom from the ages
    - The Quantum Poet will explore how progress exists in superposition
    
    Discuss this together, debate your points, acknowledge each other's arguments, 
    and ultimately try to create a synthesis that honors all perspectives. 
    Don't hold back - this is a passionate philosophical debate!"""

    print("📜 THE QUESTION:\n")
    print(debate_topic)
    print("\n" + "─" * 80 + "\n")
    
    print("🎬 Let the debate begin...\n")
    print("─" * 80 + "\n")

    # Execute the debate
    result = await orchestrated.execute_task(debate_topic)

    # Display the fascinating conversation
    if result.success:
        print("\n" + "═" * 80)
        print("  💬 THE DEBATE UNFOLDS 💬")
        print("═" * 80 + "\n")
        
        # Show all agent messages
        for i, msg in enumerate(result.workspace_messages, 1):
            msg_type = msg.get('message_type', 'unknown')
            sender = msg.get('sender_name', 'Unknown')
            content = msg.get('content', '')
            
            # Skip system messages
            if msg_type == 'system':
                continue
            
            # Beautiful formatting for each philosopher
            icons = {
                'EternalOptimist': '☀️💫',
                'PragmaticCynic': '🌧️⚡',
                'SentientLibrary': '📚📖',
                'QuantumPoet': '⚛️✨',
            }
            
            icon = icons.get(sender, '💬')
            
            print(f"{icon} {sender} speaks:")
            print(f"{'─' * 76}")
            
            for line in content.split('\n'):
                if line.strip():
                    print(f"  {line}")
            
            print(f"\n")

        print("═" * 80)
        print("  🎭 THE SYNTHESIS 🎭")
        print("═" * 80 + "\n")
        
        print("After much debate, here is their collective wisdom:\n")
        
        for line in result.final_result.split('\n'):
            if line.strip():
                print(f"  {line}")
        
        print("\n" + "═" * 80)
        print("  📊 DEBATE STATISTICS 📊")
        print("═" * 80 + "\n")
        
        print(f"  • Total subtasks: {len(result.plan.subtasks)}")
        print(f"  • Total messages: {len(result.workspace_messages)}")
        print(f"  • Participating agents: {len(result.plan.selected_agents)}")
        print(f"  • Execution stages: {len(result.plan.execution_order)}")
        
        print("\n  Orchestrator's Strategy:")
        reasoning_lines = result.plan.reasoning.split('\n')
        for line in reasoning_lines:
            if line.strip():
                print(f"    {line}")
        
        print("\n" + "═" * 80 + "\n")

    else:
        print(f"❌ The debate collapsed: {result.error}\n")

    # Cleanup
    print("🌙 The debate chamber closes...\n")
    
    await optimist_server.stop()
    await cynic_server.stop()
    await library_server.stop()
    await quantum_server.stop()

    print("═" * 80)
    print("  ✨ May we meet again in the realm of ideas! ✨")
    print("═" * 80 + "\n")


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

