"""
Minimal Synqed Demo - REAL-TIME AI-to-AI Interaction
====================================================

Watch AI agents collaborate in REAL-TIME! This demo shows:

✓ Agent creation with real LLMs (OpenAI GPT-4)
✓ Agent servers running on different ports
✓ Orchestrator with intelligent routing
✓ OrchestratedWorkspace with task decomposition
✓ TRUE AI-to-AI collaboration (agents discuss & give feedback!)
✓ REAL-TIME message streaming - see every interaction as it happens!
✓ Multi-phase collaboration:
    Phase 1: Kickoff - agents get their assignments
    Phase 2: Proposals - agents share their initial approach
    Phase 3: Feedback - agents review and comment on each other's work
    Phase 4: Refinement - agents incorporate peer feedback

Setup:
    pip install synqed openai python-dotenv
    echo 'OPENAI_API_KEY=your-key' > .env
    python minimal_full_demo.py

What you'll see:
    🔬 Researcher analyzes user behavior patterns
    🎨 Designer creates UI/UX based on research
    💻 Developer implements technical features
    Then they DISCUSS and REFINE together - all in real-time!
"""

import asyncio
import os
from pathlib import Path
from dotenv import load_dotenv
from openai import AsyncOpenAI
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("❌ Set OPENAI_API_KEY in .env file")
        return

    print("\n🚀 MINIMAL SYNQED FULL DEMO - ALL FEATURES\n" + "="*60 + "\n")

    # ============================================
    # FEATURE 1: Create Specialized Agents
    # ============================================
    async def llm_executor(context):
        """Real LLM executor - agents get full workspace context"""
        client = AsyncOpenAI(api_key=api_key)
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": "You are a specialized AI agent."},
                {"role": "user", "content": context.get_user_input()}
            ]
        )
        return response.choices[0].message.content

    # Three specialized agents
    researcher = synqed.Agent(
        name="Researcher",
        description="Gathers data and analyzes trends",
        skills=["research", "data-analysis"],
        executor=llm_executor
    )
    
    designer = synqed.Agent(
        name="Designer", 
        description="Creates UI/UX designs and user experiences",
        skills=["design", "user-experience", "prototyping"],
        executor=llm_executor
    )
    
    developer = synqed.Agent(
        name="Developer",
        description="Implements technical solutions and writes code",
        skills=["coding", "implementation", "architecture"],
        executor=llm_executor
    )

    print("✓ Created 3 specialized agents\n")

    # ============================================
    # FEATURE 2: Start Agent Servers
    # ============================================
    servers = [
        synqed.AgentServer(researcher, port=8001),
        synqed.AgentServer(designer, port=8002),
        synqed.AgentServer(developer, port=8003)
    ]
    
    for server in servers:
        await server.start_background()
    print("✓ Started 3 agent servers\n")

    # ============================================
    # FEATURE 3: Create Orchestrator (LLM-powered routing)
    # ============================================
    orchestrator = synqed.Orchestrator(
        provider=synqed.LLMProvider.OPENAI,
        api_key=api_key,
        model="gpt-4o"
    )
    print("✓ Created orchestrator with GPT-4o\n")

    # ============================================
    # FEATURE 4: Real-time Message Streaming Callback
    # ============================================
    message_count = {"count": 0}  # Track messages
    current_phase = {"phase": ""}
    
    def real_time_message_handler(msg_dict):
        """Callback that shows AI-to-AI interactions in REAL-TIME!"""
        message_count["count"] += 1
        
        sender = msg_dict.get('sender_name', 'System')
        content = msg_dict.get('content', '')
        msg_type = msg_dict.get('message_type', 'message')
        metadata = msg_dict.get('metadata', {})
        phase = metadata.get('phase', '')
        
        # Track phase changes
        if phase and phase != current_phase["phase"]:
            current_phase["phase"] = phase
            print(f"\n{'='*60}")
            print(f"🔄 PHASE: {phase.upper()}")
            print(f"{'='*60}\n")
        
        # Format based on sender and type
        if sender == "System":
            icon = "📢"
            color_start = "\033[96m"  # Cyan
        elif sender == "Researcher":
            icon = "🔬"
            color_start = "\033[94m"  # Blue
        elif sender == "Designer":
            icon = "🎨"
            color_start = "\033[95m"  # Magenta
        elif sender == "Developer":
            icon = "💻"
            color_start = "\033[92m"  # Green
        else:
            icon = "💬"
            color_start = "\033[97m"  # White
        
        color_end = "\033[0m"  # Reset
        
        # Show message in real-time
        if msg_type == "system":
            print(f"{icon} {color_start}[{sender}]{color_end} {content[:200]}")
        else:
            # Truncate long messages for readability
            display_content = content[:300] + "..." if len(content) > 300 else content
            print(f"{icon} {color_start}{sender}:{color_end}")
            print(f"   {display_content}\n")
    
    # ============================================
    # FEATURE 5: OrchestratedWorkspace with TRUE collaboration
    # ============================================
    workspace = synqed.OrchestratedWorkspace(
        orchestrator=orchestrator,
        enable_agent_discussion=True,  # 🔑 This enables AI-to-AI interaction!
        message_callback=real_time_message_handler  # 🔑 Real-time streaming!
    )
    
    workspace.register_agent(researcher)
    workspace.register_agent(designer)
    workspace.register_agent(developer)
    
    print("✓ Created collaborative workspace with real-time streaming\n")

    # ============================================
    # FEATURE 6: Execute Complex Task - Watch in Real-Time!
    # ============================================
    print("="*60)
    print("TASK: Design a habit-tracking mobile app feature")
    print("="*60)
    print("\n🎬 WATCH AI AGENTS COLLABORATE IN REAL-TIME:\n")
    print("Watch as agents:")
    print("  1. Receive their assignments")
    print("  2. Share initial proposals")
    print("  3. Give FEEDBACK to each other (AI-to-AI!)")
    print("  4. Refine their work based on peer insights")
    print("\n" + "="*60 + "\n")

    # This single call orchestrates everything - watch the magic unfold!
    result = await workspace.execute_task(
        "Design a mobile app feature for daily habit tracking with streaks and reminders"
    )

    # ============================================
    # FEATURE 7: Results Summary
    # ============================================
    print("\n" + "="*60)
    print("📊 COLLABORATION SUMMARY")
    print("="*60 + "\n")
    
    if result.success:
        print(f"✅ Success! {message_count['count']} messages exchanged\n")
        
        # Show the execution plan
        print(f"📋 Execution Plan:")
        print(f"   • Subtasks created: {len(result.plan.subtasks)}")
        print(f"   • Agents involved: {', '.join(result.plan.selected_agents)}")
        print(f"   • Execution stages: {len(result.plan.execution_order)}\n")
        
        # Show final result
        print("="*60)
        print("🎉 FINAL INTEGRATED RESULT")
        print("="*60 + "\n")
        print(result.final_result[:600] + ("..." if len(result.final_result) > 600 else "") + "\n")
    else:
        print(f"❌ Failed: {result.error}\n")

    # Cleanup
    for server in servers:
        await server.stop()
    
    print("="*60)
    print("✓ Demo complete! All features demonstrated.")
    print("="*60 + "\n")


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

