#!/usr/bin/env python3
"""
Parallel Workflow Example

Demonstrates how to execute multiple tasks in parallel
using the SwarmCoordinator.

Usage:
    python examples/workflows/parallel_workflow.py
"""

import asyncio
import logging

from agent_orchestrator import Orchestrator
from agent_orchestrator.swarm import (
    SwarmCoordinator,
    CoordinationStrategy,
    TaskDecomposer,
    DecompositionStrategy,
    ResultAggregator,
    AggregationStrategy,
)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def main():
    """Execute tasks in parallel across multiple agents."""

    orchestrator = Orchestrator()

    try:
        await orchestrator.start()

        # Create swarm coordinator
        coordinator = SwarmCoordinator(
            strategy=CoordinationStrategy.LOAD_BALANCED,
            max_concurrent=3,
        )

        # Register available agents
        agents = await orchestrator.list_agents()
        for agent in agents:
            if agent.status == "available":
                coordinator.register_agent(agent.agent_id, agent.capabilities)

        # Define parallel tasks
        tasks = [
            {
                "id": "backend-api",
                "prompt": "Design a REST API for a todo list application",
            },
            {
                "id": "database-schema",
                "prompt": "Design a database schema for a todo list application",
            },
            {
                "id": "frontend-components",
                "prompt": "Design React components for a todo list UI",
            },
        ]

        logger.info(f"Executing {len(tasks)} tasks in parallel...")

        # Execute in parallel
        results = await coordinator.execute_parallel(tasks, timeout=300)

        # Display results
        print("\n" + "=" * 60)
        print("PARALLEL EXECUTION RESULTS")
        print("=" * 60)

        for task_id, result in results.items():
            status = "✅" if result.success else "❌"
            print(f"\n{status} {task_id}")
            print(f"   Agent: {result.agent_id}")
            print(f"   Duration: {result.duration_seconds:.1f}s")
            if result.success:
                print(f"   Output: {result.output[:200]}...")
            else:
                print(f"   Error: {result.error}")

        # Aggregate results
        aggregator = ResultAggregator(strategy=AggregationStrategy.MERGE)
        combined = aggregator.aggregate(results)

        print("\n" + "=" * 60)
        print("COMBINED RESULT")
        print("=" * 60)
        print(combined)

    finally:
        await orchestrator.shutdown()


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