"""
Safety 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="safety")
def safety():
    """
    Manage safety systems and monitoring.
    
    Examples:
        nwo safety enable --agent bot_001 --response-time 10
    """
    pass


@safety.command(name="enable")
@click.option("--agent", "agent_id", required=True, help="Agent/robot ID")
@click.option("--response-time", default=10, help="Response time in milliseconds")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def enable_safety(agent_id, response_time, json_output):
    """Enable real-time safety monitoring."""
    try:
        client = NWOClient()
        
        with console.status(f"[bold green]Enabling safety monitoring for {agent_id}..."):
            result = client.enable_realtime_safety(agent_id, response_time)
        
        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 enable safety')}")
            return
        
        config = result.get("safety_config", {})
        
        console.print(Panel(
            f"[bold green]✓ Real-Time Safety Enabled[/bold green]\n\n"
            f"[cyan]Agent:[/cyan] {result.get('agent_id', agent_id)}\n"
            f"[cyan]Status:[/cyan] {config.get('status', 'active')}\n"
            f"[cyan]Response Time:[/cyan] {config.get('response_time_ms', response_time)}ms\n"
            f"[cyan]Monitoring:[/cyan] {config.get('monitoring_level', 'standard')}",
            title="Safety System",
            border_style="green"
        ))
        
        monitored = config.get("monitored_parameters", [])
        if monitored:
            console.print("\n[bold]Monitored:[/bold]")
            for param in monitored:
                console.print(f"  • {param}")
        
    except NWOAPIError as e:
        handle_error(e)


@safety.command(name="status")
@click.option("--agent", "agent_id", help="Agent/robot ID")
def safety_status(agent_id):
    """Check safety system status."""
    console.print("[yellow]Safety status requires WebSocket connection (v2.1)[/yellow]")
