"""
Basic Workspace Example

This example demonstrates the basic usage of Synqed Workspace for
agent collaboration and resource sharing.

Setup:
1. Install: pip install synqed openai python-dotenv
2. Create .env file with: OPENAI_API_KEY='your-key-here'
3. Run: python workspace_basic.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("  BASIC WORKSPACE EXAMPLE")
    print("=" * 70 + "\n")

    # Step 1: Create agents with different specializations
    print("📦 Creating specialized agents...\n")

    async def recipe_executor(context):
        """Recipe agent that suggests meals."""
        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 recipe expert. Suggest delicious recipes based on user requests.",
                },
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    async def shopping_executor(context):
        """Shopping agent that creates shopping lists."""
        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 shopping assistant. Create organized shopping lists based on recipes or meal plans.",
                },
                {"role": "user", "content": user_message},
            ],
        )
        return response.choices[0].message.content

    # Create agents
    recipe_agent = synqed.Agent(
        name="RecipeAgent",
        description="Expert in suggesting recipes and meal ideas",
        skills=["recipe_search", "meal_planning"],
        executor=recipe_executor,
    )

    shopping_agent = synqed.Agent(
        name="ShoppingAgent",
        description="Creates organized shopping lists",
        skills=["shopping_list", "ingredient_organization"],
        executor=shopping_executor,
    )

    print("✓ Created RecipeAgent")
    print("✓ Created ShoppingAgent\n")

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

    recipe_server = synqed.AgentServer(recipe_agent, port=8001)
    shopping_server = synqed.AgentServer(shopping_agent, port=8002)

    await recipe_server.start_background()
    await shopping_server.start_background()

    print(f"✓ RecipeAgent running at {recipe_agent.url}")
    print(f"✓ ShoppingAgent running at {shopping_agent.url}\n")

    # Step 3: Create a workspace
    print("🏗️  Creating workspace...\n")

    workspace = synqed.Workspace(
        name="Meal Planning Workspace",
        description="Collaborative space for planning meals and creating shopping lists",
        auto_cleanup=True,
    )

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

    # Step 4: Add agents to workspace
    print("👥 Adding agents to workspace...\n")

    workspace.add_agent(recipe_agent)
    workspace.add_agent(shopping_agent)

    participants = workspace.list_participants()
    print(f"✓ Added {len(participants)} agents to workspace")
    for p in participants:
        print(f"  • {p['name']} ({p['role']})")
    print()

    # Step 5: Start the workspace
    print("▶️  Starting workspace...\n")
    await workspace.start()
    print(f"✓ Workspace state: {workspace.state.value}\n")

    # Step 6: Collaborate on a task
    print("=" * 70)
    print("COLLABORATIVE TASK")
    print("=" * 70 + "\n")

    task = "Plan a healthy dinner for tonight and create a shopping list for it"
    print(f"Task: {task}\n")
    print("🤖 Agents are collaborating...\n")

    # Execute collaborative task
    results = await workspace.collaborate(task)

    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 7: Send direct message to specific agent
    print("=" * 70)
    print("DIRECT MESSAGING")
    print("=" * 70 + "\n")

    recipe_participant_id = participants[0]["participant_id"]
    direct_message = "What's a quick pasta recipe?"

    print(f"Sending to RecipeAgent: {direct_message}\n")

    response = await workspace.send_message_to_agent(
        recipe_participant_id, direct_message
    )

    print(f"RecipeAgent: {response}\n")

    # Step 8: View workspace artifacts
    print("=" * 70)
    print("WORKSPACE ARTIFACTS")
    print("=" * 70 + "\n")

    artifacts = workspace.get_artifacts()
    print(f"Total artifacts: {len(artifacts)}\n")

    for artifact in artifacts:
        print(f"📦 {artifact.name}")
        print(f"   Type: {artifact.artifact_type}")
        print(f"   Created by: {artifact.created_by}")
        print(f"   Created at: {artifact.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
        print()

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

    messages = workspace.get_messages(limit=10)
    print(f"Recent messages ({len(messages)}):\n")

    for msg in messages[-5:]:  # Show last 5 messages
        print(f"[{msg.timestamp.strftime('%H:%M:%S')}] {msg.sender_name}:")
        print(f"  {msg.content[:100]}...")
        print()

    # Step 10: Export workspace
    print("=" * 70)
    print("EXPORT")
    print("=" * 70 + "\n")

    export_path = await workspace.export_workspace()
    print(f"✓ Workspace exported to: {export_path}\n")

    # Step 11: Complete and close workspace
    print("🏁 Completing workspace...\n")

    await workspace.complete()
    print(f"✓ Workspace state: {workspace.state.value}")

    await workspace.close()
    print("✓ Workspace closed and cleaned up\n")

    # Stop servers
    print("🛑 Stopping agent servers...\n")
    await recipe_server.stop()
    await shopping_server.stop()
    print("✓ All servers stopped\n")

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


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

