"""
Daemon management CLI commands.
"""

from typing import Optional

import typer
from rich.console import Console

from airctl.cli.output import OutputFormatter

app = typer.Typer(help="Daemon management commands")
console = Console()


@app.command("status")
def daemon_status(
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
) -> None:
    """Check daemon status."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        from airctl.ipc.client import DaemonClient
        
        client = DaemonClient()
        if client.is_running():
            result = {"running": True, "pid": client.get_pid()}
            formatter.print(result)
        else:
            formatter.print({"running": False})
    except Exception as e:
        formatter.print_error(str(e))


@app.command("start")
def daemon_start(
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
    log_level: str = typer.Option("INFO", "--log-level", help="Log level"),
) -> None:
    """Start the BLE daemon."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        from airctl.daemon.auto_start import ensure_daemon_running
        
        pid = ensure_daemon_running(log_level=log_level)
        formatter.print_success("Daemon started", {"pid": pid})
    except Exception as e:
        formatter.print_error(str(e))


@app.command("stop")
def daemon_stop(
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
) -> None:
    """Stop the BLE daemon."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        import time
        from airctl.ipc.client import DaemonClient
        
        client = DaemonClient()
        if not client.is_running():
            formatter.print_success("Daemon already stopped")
            return

        if client.stop_daemon():
            for _ in range(20):
                time.sleep(0.5)
                if not client.is_running():
                    break
            formatter.print_success("Daemon stopped")
        else:
            formatter.print_error("Failed to stop daemon")
    except Exception as e:
        formatter.print_error(str(e))


@app.command("restart")
def daemon_restart(
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
    log_level: str = typer.Option("INFO", "--log-level", help="Log level"),
) -> None:
    """Restart the BLE daemon."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        import time
        from airctl.ipc.client import DaemonClient
        from airctl.daemon.auto_start import ensure_daemon_running
        
        client = DaemonClient()
        if client.is_running():
            client.stop_daemon()
            for _ in range(20):
                time.sleep(0.5)
                if not client.is_running():
                    break
        
        pid = ensure_daemon_running(log_level=log_level)
        formatter.print_success("Daemon restarted", {"pid": pid})
    except Exception as e:
        formatter.print_error(str(e))
