"""
Orchestrated Workspace Example

This example demonstrates using Workspace with Orchestrator for
intelligent agent selection and collaboration.

Setup:
1. Install: pip install synqed openai python-dotenv
2. Create .env file with: OPENAI_API_KEY='your-key-here'
3. Run: python workspace_orchestrated.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():
    # Check for API key
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        print("❌ Please set OPENAI_API_KEY in your .env file")
        return

    print("\n" + "=" * 70)
    print("  ORCHESTRATED WORKSPACE EXAMPLE")
    print("=" * 70 + "\n")

    # Step 1: Create orchestrator
    print("🎯 Creating orchestrator...\n")

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

    print("✓ Orchestrator created\n")

    # Step 2: Create specialized agents
    print("📦 Creating specialized agents...\n")

    async def research_executor(context):
        """Research agent."""
        user_message = context.get_user_input()
        from openai import AsyncOpenAI

        client = AsyncOpenAI(api_key=api_key)
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {
                    "role": "system",
                    "content": "You are a research expert. Provide detailed, well-researched information on any topic.",
                },
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    async def writing_executor(context):
        """Writing agent."""
        user_message = context.get_user_input()
        from openai import AsyncOpenAI

        client = AsyncOpenAI(api_key=api_key)
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {
                    "role": "system",
                    "content": "You are a professional writer. Create engaging, well-structured content.",
                },
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    async def coding_executor(context):
        """Coding agent."""
        user_message = context.get_user_input()
        from openai import AsyncOpenAI

        client = AsyncOpenAI(api_key=api_key)
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {
                    "role": "system",
                    "content": "You are a programming expert. Provide code examples and technical explanations.",
                },
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    # Create agents with detailed skills
    research_agent = synqed.Agent(
        name="ResearchAgent",
        description="Conducts research and gathers information on various topics",
        skills=[
            {
                "skill_id": "research",
                "name": "Research",
                "description": "Conduct thorough research on any topic",
                "tags": ["research", "information", "analysis"],
            },
            {
                "skill_id": "fact_checking",
                "name": "Fact Checking",
                "description": "Verify facts and sources",
                "tags": ["facts", "verification", "accuracy"],
            },
        ],
        executor=research_executor,
    )

    writing_agent = synqed.Agent(
        name="WritingAgent",
        description="Creates professional written content",
        skills=[
            {
                "skill_id": "content_writing",
                "name": "Content Writing",
                "description": "Write engaging articles and content",
                "tags": ["writing", "content", "articles"],
            },
            {
                "skill_id": "editing",
                "name": "Editing",
                "description": "Edit and improve written content",
                "tags": ["editing", "proofreading", "improvement"],
            },
        ],
        executor=writing_executor,
    )

    coding_agent = synqed.Agent(
        name="CodingAgent",
        description="Provides programming solutions and code examples",
        skills=[
            {
                "skill_id": "code_generation",
                "name": "Code Generation",
                "description": "Generate code in various languages",
                "tags": ["coding", "programming", "development"],
            },
            {
                "skill_id": "code_review",
                "name": "Code Review",
                "description": "Review and optimize code",
                "tags": ["review", "optimization", "best practices"],
            },
        ],
        executor=coding_executor,
    )

    print("✓ Created ResearchAgent")
    print("✓ Created WritingAgent")
    print("✓ Created CodingAgent\n")

    # Step 3: Start servers
    print("🚀 Starting agent servers...\n")

    research_server = synqed.AgentServer(research_agent, port=8001)
    writing_server = synqed.AgentServer(writing_agent, port=8002)
    coding_server = synqed.AgentServer(coding_agent, port=8003)

    await research_server.start_background()
    await writing_server.start_background()
    await coding_server.start_background()

    print(f"✓ ResearchAgent: {research_agent.url}")
    print(f"✓ WritingAgent: {writing_agent.url}")
    print(f"✓ CodingAgent: {coding_agent.url}\n")

    # Step 4: Create workspace
    print("🏗️  Creating workspace with orchestrator...\n")

    workspace = synqed.Workspace(
        name="Content Creation Workspace",
        description="Collaborative workspace for research, writing, and coding",
        auto_cleanup=True,
    )

    print(f"✓ Workspace: {workspace.name}\n")

    # Step 5: Add agents
    workspace.add_agent(research_agent)
    workspace.add_agent(writing_agent)
    workspace.add_agent(coding_agent)

    print(f"✓ Added {len(workspace.list_participants())} agents\n")

    # Step 6: Start workspace
    await workspace.start()
    print(f"✓ Workspace active\n")

    # Step 7: Collaborate with orchestrator
    print("=" * 70)
    print("ORCHESTRATED COLLABORATION")
    print("=" * 70 + "\n")

    task = "Research microservices architecture, then explain it in simple terms with a Python code example"

    print(f"Complex Task:\n{task}\n")
    print("🎯 Orchestrator analyzing task...")
    print("🤖 Selecting best agents...\n")

    # The orchestrator will intelligently select which agents to use
    results = await workspace.collaborate(task, orchestrator=orchestrator)

    print("=" * 70)
    print("RESULTS")
    print("=" * 70 + "\n")

    for agent_name, response in results.items():
        print(f"📝 {agent_name}:")
        print(f"{response}\n")
        print("-" * 70 + "\n")

    # Step 8: Try a different task that requires different agents
    print("=" * 70)
    print("SECOND TASK")
    print("=" * 70 + "\n")

    task2 = "Write a technical blog post about Python async/await"
    print(f"Task: {task2}\n")
    print("🎯 Orchestrator selecting agents...\n")

    results2 = await workspace.collaborate(task2, orchestrator=orchestrator)

    print("=" * 70)
    print("RESULTS")
    print("=" * 70 + "\n")

    for agent_name, response in results2.items():
        print(f"📝 {agent_name}:")
        print(f"{response[:200]}...")  # Truncate for brevity
        print()

    # Step 9: View artifacts
    print("=" * 70)
    print("WORKSPACE SUMMARY")
    print("=" * 70 + "\n")

    artifacts = workspace.get_artifacts()
    messages = workspace.get_messages()

    print(f"Total artifacts: {len(artifacts)}")
    print(f"Total messages: {len(messages)}")
    print(f"Participants: {len(workspace.list_participants())}\n")

    # Step 10: Export and close
    print("💾 Exporting workspace...\n")
    export_path = await workspace.export_workspace()
    print(f"✓ Exported to: {export_path}\n")

    await workspace.complete()
    await workspace.close()

    print("🛑 Stopping servers...\n")
    await research_server.stop()
    await writing_server.stop()
    await coding_server.stop()

    print("=" * 70)
    print("✓ Example completed successfully!")
    print("=" * 70 + "\n")


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

