"""
Doctor diagnostic command for AirCli.
"""

import platform
import sys

import typer
from rich.console import Console
from rich.table import Table

from airctl.cli.output import OutputFormatter

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

OK = "[OK]"
WARN = "[WARN]"
ERR = "[ERR]"


@app.command("check")
def doctor_check(
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
) -> None:
    """Run diagnostic checks on AirCli configuration and connectivity."""
    formatter = OutputFormatter(json_output=not human)
    
    checks = []
    
    console.print()
    console.print("[bold]AirCli Doctor[/bold]")
    console.print("[dim]----------------[/dim]")
    console.print()
    
    check_config(checks)
    check_daemon(checks)
    check_bluetooth_adapter(checks)
    check_connected_devices(checks)
    
    if not human:
        formatter.print({"checks": checks, "passed": all(c["status"] == "ok" for c in checks)})
    else:
        print_summary(checks)


def check_config(checks: list) -> None:
    """Check configuration file."""
    from airctl.config.manager import ConfigManager
    from airctl.config.defaults import get_default_config_path
    
    config_path = get_default_config_path()
    
    try:
        config = ConfigManager()
        aliases_count = len(config.get("aliases", {}))
        presets_count = len(config.list_presets())
        
        checks.append({
            "name": "Configuration",
            "status": "ok",
            "message": f"Config file exists ({aliases_count} aliases, {presets_count} presets)",
            "details": {"path": config_path, "aliases": aliases_count, "presets": presets_count},
        })
        console.print(f"[green]{OK}[/green] Configuration: Config file exists ({aliases_count} aliases, {presets_count} presets)")
    except Exception as e:
        checks.append({
            "name": "Configuration",
            "status": "error",
            "message": str(e),
            "details": {"path": config_path},
        })
        console.print(f"[red]{ERR}[/red] Configuration: {e}")


def check_daemon(checks: list) -> None:
    """Check daemon status."""
    from airctl.ipc.client import DaemonClient
    
    try:
        client = DaemonClient()
        if client.is_running():
            pid = client.get_pid()
            checks.append({
                "name": "Daemon",
                "status": "ok",
                "message": f"Daemon running (PID: {pid})",
                "details": {"running": True, "pid": pid},
            })
            console.print(f"[green]{OK}[/green] Daemon: Running (PID: {pid})")
        else:
            checks.append({
                "name": "Daemon",
                "status": "warning",
                "message": "Daemon not running (will auto-start on first command)",
                "details": {"running": False, "pid": None},
            })
            console.print(f"[yellow]{WARN}[/yellow] Daemon: Not running (will auto-start on first command)")
    except Exception as e:
        checks.append({
            "name": "Daemon",
            "status": "error",
            "message": str(e),
            "details": {"running": False},
        })
        console.print(f"[red]{ERR}[/red] Daemon: {e}")


def check_bluetooth_adapter(checks: list) -> None:
    """Check Bluetooth adapter status."""
    import asyncio
    
    try:
        from bleak import BleakScanner
        
        async def check_adapter():
            try:
                scanner = BleakScanner()
                await scanner.start()
                await asyncio.sleep(0.5)
                await scanner.stop()
                return True
            except Exception:
                return False
        
        if asyncio.run(check_adapter()):
            checks.append({
                "name": "Bluetooth Adapter",
                "status": "ok",
                "message": "Bluetooth adapter available",
                "details": {"available": True},
            })
            console.print(f"[green]{OK}[/green] Bluetooth Adapter: Available")
        else:
            checks.append({
                "name": "Bluetooth Adapter",
                "status": "error",
                "message": "Bluetooth adapter not available or no permission",
                "details": {"available": False},
            })
            console.print(f"[red]{ERR}[/red] Bluetooth Adapter: Not available or no permission")
    except Exception as e:
        checks.append({
            "name": "Bluetooth Adapter",
            "status": "error",
            "message": str(e),
            "details": {"available": False},
        })
        console.print(f"[red]{ERR}[/red] Bluetooth Adapter: {e}")


def check_connected_devices(checks: list) -> None:
    """Check connected devices."""
    from airctl.ipc.client import DaemonClient
    
    try:
        client = DaemonClient()
        if not client.is_running():
            checks.append({
                "name": "Connected Devices",
                "status": "warning",
                "message": "Daemon not running, cannot check devices",
                "details": {"count": 0, "devices": []},
            })
            console.print(f"[yellow]{WARN}[/yellow] Connected Devices: Daemon not running")
            return
        
        result = client.list_devices()
        devices = result.get("devices", [])
        count = len(devices)
        
        if count > 0:
            device_names = [d.get("name") or d.get("address") for d in devices]
            checks.append({
                "name": "Connected Devices",
                "status": "ok",
                "message": f"{count} device(s) connected",
                "details": {"count": count, "devices": device_names},
            })
            console.print(f"[green]{OK}[/green] Connected Devices: {count} device(s)")
        else:
            checks.append({
                "name": "Connected Devices",
                "status": "ok",
                "message": "No devices connected",
                "details": {"count": 0, "devices": []},
            })
            console.print(f"[green]{OK}[/green] Connected Devices: No devices connected")
    except Exception as e:
        checks.append({
            "name": "Connected Devices",
            "status": "warning",
            "message": str(e),
            "details": {"count": 0},
        })
        console.print(f"[yellow]{WARN}[/yellow] Connected Devices: {e}")


def print_summary(checks: list) -> None:
    """Print summary of all checks."""
    console.print()
    
    passed = sum(1 for c in checks if c["status"] == "ok")
    warnings = sum(1 for c in checks if c["status"] == "warning")
    errors = sum(1 for c in checks if c["status"] == "error")
    
    console.print("[dim]----------------[/dim]")
    console.print(f"Total: {passed} passed, {warnings} warnings, {errors} errors")
    console.print()
    
    if errors == 0:
        console.print("[green]All critical checks passed![/green]")
    else:
        console.print("[red]Some checks failed. Please fix the errors above.[/red]")
    
    console.print()
    console.print("[dim]System Information:[/dim]")
    console.print(f"  Python: {sys.version.split()[0]}")
    console.print(f"  Platform: {platform.system()} {platform.release()}")
    console.print(f"  Architecture: {platform.machine()}")
    console.print()
