"""
Robot commands for NWO CLI
"""

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

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

console = Console()


@click.group(name="robot")
def robot():
    """
    Control individual robots and send commands.
    
    Examples:
        nwo robot "pick up the red box"
        nwo robot "navigate to kitchen" --agent bot_001
        nwo robot "inspect the area" --camera http://cam.local/image.jpg
    """
    pass


@robot.command()
@click.argument("instruction")
@click.option("--agent", "-a", help="Target robot/agent ID")
@click.option("--camera", "-c", help="Camera/image URL for vision tasks")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def send(instruction, agent, camera, json_output):
    """
    Send a natural language command to a robot.
    
    INSTRUCTION: What you want the robot to do (e.g., "pick up the box")
    """
    try:
        client = NWOClient()
        
        with console.status("[bold green]Sending command to robot..."):
            result = client.inference(instruction, image_url=camera)
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        # Pretty output
        data = result.get("data", {})
        routing = result.get("routing", {})
        selected = routing.get("selected_model", {})
        
        console.print(Panel(
            f"[bold green]✓ Command Executed Successfully[/bold green]\n\n"
            f"[cyan]Instruction:[/cyan] {instruction}\n"
            f"[cyan]Agent:[/cyan] {result.get('agent', 'Unknown')}\n"
            f"[cyan]Key Type:[/cyan] {result.get('key_type', 'unknown')}",
            title="Robot Response",
            border_style="green"
        ))
        
        # Model routing info
        console.print("\n[bold]Model Routing:[/bold]")
        routing_table = Table(show_header=False, box=None)
        routing_table.add_row("Task Type:", routing.get("task_type", "general").upper())
        routing_table.add_row("Selected Model:", selected.get("name", "Xiaomi Robotics-0"))
        routing_table.add_row("Provider:", selected.get("provider", "xiaomi").upper())
        routing_table.add_row("Score:", f"{selected.get('score', 100)}/100")
        routing_table.add_row("Reason:", routing.get("reason", "Default"))
        console.print(routing_table)
        
        # Performance metrics
        console.print("\n[bold]Performance:[/bold]")
        perf_table = Table(show_header=False, box=None)
        perf_table.add_row("Confidence:", f"{data.get('confidence', 0) * 100:.1f}%")
        perf_table.add_row("Inference Time:", f"{data.get('inference_time_ms', 0)}ms")
        perf_table.add_row("Total Latency:", f"{data.get('total_latency_ms', 0)}ms")
        perf_table.add_row("Actions Generated:", str(data.get('action_count', 0)))
        console.print(perf_table)
        
        # Sample actions
        actions = data.get("actions", [])
        if actions:
            console.print("\n[bold]Sample Actions:[/bold]")
            for i, action in enumerate(actions[:3], 1):
                action_json = json.dumps(action, indent=2)
                console.print(Syntax(action_json, "json", theme="monokai"))
            if len(actions) > 3:
                console.print(f"[dim]... and {len(actions) - 3} more actions[/dim]")
                
    except NWOAPIError as e:
        handle_error(e)


@robot.command()
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def health(json_output):
    """Check API health status."""
    try:
        client = NWOClient()
        
        with console.status("[bold green]Checking API health..."):
            result = client.health_check()
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        status_color = "green" if result.get("status") == "ok" else "red"
        
        console.print(Panel(
            f"[bold {status_color}]● {result.get('status', 'unknown').upper()}[/bold {status_color}]\n\n"
            f"[cyan]Server Time:[/cyan] {result.get('time', 'N/A')}\n"
            f"[cyan]Version:[/cyan] {result.get('version', '2.0.0')}\n"
            f"[cyan]Features:[/cyan] {', '.join(result.get('features', ['inference']))}",
            title="API Health",
            border_style=status_color
        ))
        
    except NWOAPIError as e:
        handle_error(e)


@robot.command(name="list")
def list_robots():
    """List available robots/agents."""
    console.print("[yellow]This feature requires the Fleet Management API.[/yellow]")
    console.print("Visit https://nwo.capital/webapp/api-key.php to view your robots.")


@robot.command()
@click.argument("task")
@click.option("--object", "object_type", help="Object type for learning (e.g., glass, metal)")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def learn(task, object_type, json_output):
    """
    Get learned parameters for a specific task.
    
    TASK: Type of task (pick_object, place_object, navigate, inspect, general)
    """
    try:
        client = NWOClient()
        
        with console.status(f"[bold green]Getting learned parameters for '{task}'..."):
            result = client.get_learned_params(task, object_type)
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        if not result.get("success"):
            console.print(f"[yellow]No learned parameters found for '{task}'.[/yellow]")
            console.print("[dim]Try recording some outcomes first using the API.[/dim]")
            return
        
        console.print(Panel(
            f"[bold cyan]Task:[/bold cyan] {task}\n"
            f"[cyan]Object Type:[/cyan] {object_type or 'General'}\n"
            f"[cyan]Success Rate:[/cyan] {result.get('success_rate', 'N/A')}\n"
            f"[cyan]Total Attempts:[/cyan] {result.get('total_attempts', 0)}",
            title="Learned Parameters",
            border_style="cyan"
        ))
        
        params = result.get("parameters", {})
        if params:
            console.print("\n[bold]Optimized Parameters:[/bold]")
            param_table = Table(show_header=True, header_style="bold magenta")
            param_table.add_column("Parameter")
            param_table.add_column("Value")
            for key, value in params.items():
                param_table.add_row(key, str(value))
            console.print(param_table)
        
        suggestions = result.get("suggested_adaptations", [])
        if suggestions:
            console.print("\n[bold]Suggested Adaptations:[/bold]")
            for suggestion in suggestions:
                console.print(f"  • {suggestion}")
                
    except NWOAPIError as e:
        handle_error(e)
