"""
Swarm commands for NWO CLI
"""

import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
import json

from ..client import NWOClient, NWOAPIError
from ..utils import handle_error

console = Console()


@click.group(name="swarm")
def swarm():
    """
    Manage robot swarms and multi-agent coordination.
    
    Examples:
        nwo swarm create "Warehouse Team" --strategy divide_and_conquer
        nwo swarm add-agent bot_002 --swarm swarm_abc123
        nwo swarm list
    """
    pass


@swarm.command(name="create")
@click.argument("name")
@click.option("--strategy", "-s", default="divide_and_conquer",
              type=click.Choice(["divide_and_conquer", "round_robin", "priority_queue"]),
              help="Coordination strategy")
@click.option("--coordinator", "-c", help="Coordinator agent ID")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def create_swarm(name, strategy, coordinator, json_output):
    """
    Create a new robot swarm.
    
    NAME: Name for the swarm (e.g., "Warehouse Team A")
    """
    try:
        client = NWOClient()
        
        with console.status(f"[bold green]Creating swarm '{name}'..."):
            result = client.create_swarm(name, strategy, coordinator)
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        if not result.get("success"):
            console.print(f"[red]Error:[/red] {result.get('error', 'Failed to create swarm')}")
            return
        
        console.print(Panel(
            f"[bold green]✓ Swarm Created Successfully[/bold green]\n\n"
            f"[cyan]Name:[/cyan] {result.get('name', 'N/A')}\n"
            f"[cyan]Swarm ID:[/cyan] {result.get('swarm_id', 'N/A')}\n"
            f"[cyan]Strategy:[/cyan] {result.get('strategy', 'N/A')}\n"
            f"[cyan]Max Agents:[/cyan] {result.get('max_agents', 'N/A')}",
            title="Swarm Created",
            border_style="green"
        ))
        
        console.print("\n[dim]Next steps:[/dim]")
        console.print(f"  nwo swarm add-agent <agent_id> --swarm {result.get('swarm_id', 'N/A')}")
        
    except NWOAPIError as e:
        handle_error(e)


@swarm.command(name="add-agent")
@click.argument("agent_id")
@click.option("--swarm", "swarm_id", required=True, help="Swarm ID")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def add_agent(agent_id, swarm_id, json_output):
    """
    Add an agent to a swarm.
    
    AGENT_ID: The robot/agent to add
    """
    try:
        client = NWOClient()
        
        with console.status(f"[bold green]Adding {agent_id} to swarm..."):
            result = client.add_to_swarm(swarm_id, agent_id)
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        if result.get("success"):
            console.print(f"[green]✓ Added {agent_id} to swarm {swarm_id}[/green]")
        else:
            console.print(f"[red]✗ Failed:[/red] {result.get('error', 'Unknown error')}")
        
    except NWOAPIError as e:
        handle_error(e)


@swarm.command(name="list")
def list_swarms():
    """List all swarms."""
    console.print("[yellow]Swarm listing requires Fleet Management API v2.1+[/yellow]")
    console.print("[dim]Visit https://nwo.capital/webapp/api-key.php to manage swarms.[/dim]")


@swarm.command(name="status")
@click.argument("swarm_id")
def swarm_status(swarm_id):
    """Check swarm status."""
    console.print(f"[yellow]Swarm status for {swarm_id}[/yellow]")
    console.print("[dim]This feature requires Fleet Management API v2.1+[/dim]")
