"""
IoT commands for NWO CLI
"""

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

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

console = Console()


@click.group(name="iot")
def iot():
    """
    Send IoT sensor data with robot commands.
    
    Examples:
        nwo iot send "water plants" --temp 25.5 --humidity 60
        nwo iot send "navigate" --gps 40.7128,-74.0060
        nwo iot send "avoid obstacles" --lidar 0.5,1.2,2.3
    """
    pass


@iot.command(name="send")
@click.argument("instruction")
@click.option("--gps", help="GPS coordinates (lat,lng)")
@click.option("--temp", type=float, help="Temperature in Celsius")
@click.option("--humidity", type=float, help="Humidity percentage")
@click.option("--lidar", help="LiDAR distances (comma-separated, e.g., 0.5,1.2,2.3)")
@click.option("--pressure", type=float, help="Air pressure")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def send_iot(instruction, gps, temp, humidity, lidar, pressure, json_output):
    """
    Send instruction with IoT sensor context.
    
    INSTRUCTION: Command to execute with sensor context
    """
    try:
        client = NWOClient()
        
        # Build sensor payload
        sensors = {}
        
        if gps:
            try:
                lat, lng = map(float, gps.split(","))
                sensors["gps"] = {"lat": lat, "lng": lng}
            except ValueError:
                console.print("[red]Error:[/red] GPS format should be 'lat,lng' (e.g., '40.7128,-74.0060')")
                return
        
        if temp is not None:
            sensors["temperature"] = temp
        
        if humidity is not None:
            sensors["humidity"] = humidity
        
        if pressure is not None:
            sensors["pressure"] = pressure
        
        if lidar:
            try:
                sensors["lidar"] = [float(x.strip()) for x in lidar.split(",")]
            except ValueError:
                console.print("[red]Error:[/red] LiDAR should be comma-separated numbers")
                return
        
        with console.status("[bold green]Sending IoT-enhanced command..."):
            result = client.inference(instruction, iot_sensors=sensors)
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        data = result.get("data", {})
        routing = result.get("routing", {})
        
        console.print(Panel(
            f"[bold green]✓ IoT Command Executed[/bold green]\n\n"
            f"[cyan]Instruction:[/cyan] {instruction}",
            title="IoT Response",
            border_style="green"
        ))
        
        # Show sensors used
        if sensors:
            console.print("\n[bold]Sensors Used:[/bold]")
            for key in sensors:
                console.print(f"  ✓ {key}")
        
        console.print(f"\n[cyan]Model:[/cyan] {routing.get('selected_model', {}).get('name', 'Xiaomi Robotics-0')}")
        console.print(f"[cyan]Confidence:[/cyan] {data.get('confidence', 0) * 100:.1f}%")
        console.print(f"[cyan]Actions:[/cyan] {data.get('action_count', 0)} generated")
        
    except NWOAPIError as e:
        handle_error(e)


@iot.command(name="sensors")
def list_sensors():
    """List supported IoT sensors."""
    console.print(Panel(
        "[bold]Supported IoT Sensors:[/bold]\n\n"
        "  [cyan]--gps[/cyan]        GPS coordinates (lat,lng)\n"
        "  [cyan]--temp[/cyan]       Temperature (°C)\n"
        "  [cyan]--humidity[/cyan]   Humidity (%)\n"
        "  [cyan]--pressure[/cyan]   Air pressure (hPa)\n"
        "  [cyan]--lidar[/cyan]      LiDAR distances (m)",
        title="IoT Sensors",
        border_style="cyan"
    ))
    
    console.print("\n[dim]Example:[/dim]")
    console.print("  nwo iot send 'water dry plants' --temp 28.5 --humidity 45")
