"""
Configuration CLI commands.
"""

from typing import Optional

import typer
from rich.console import Console

from airctl.cli.output import OutputFormatter

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


@app.command("list")
def config_list(
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
) -> None:
    """List all configuration."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        from airctl.config.manager import ConfigManager
        
        config = ConfigManager()
        formatter.print(config.get_all())
    except Exception as e:
        formatter.print_error(str(e))


@app.command("get")
def config_get(
    key: str = typer.Argument(..., help="Configuration key (dot notation)"),
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
) -> None:
    """Get a configuration value."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        from airctl.config.manager import ConfigManager
        
        config = ConfigManager()
        value = config.get(key)
        if value is None:
            formatter.print_error(f"Key not found: {key}")
        else:
            formatter.print({"key": key, "value": value})
    except Exception as e:
        formatter.print_error(str(e))


@app.command("set")
def config_set(
    key: str = typer.Argument(..., help="Configuration key (dot notation)"),
    value: str = typer.Argument(..., help="Configuration value"),
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
) -> None:
    """Set a configuration value."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        from airctl.config.manager import ConfigManager
        
        config = ConfigManager()
        
        try:
            import json
            parsed_value = json.loads(value)
        except json.JSONDecodeError:
            parsed_value = value
        
        config.set(key, parsed_value)
        formatter.print_success(f"Set {key} = {parsed_value}")
    except Exception as e:
        formatter.print_error(str(e))


@app.command("alias")
def config_alias(
    action: str = typer.Argument(..., help="Action: list, set, remove"),
    address: Optional[str] = typer.Argument(None, help="Device address"),
    name: Optional[str] = typer.Argument(None, help="Alias name"),
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
) -> None:
    """Manage device aliases."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        from airctl.config.manager import ConfigManager
        
        config = ConfigManager()
        
        if action == "list":
            aliases = config.get("aliases", {})
            formatter.print({"aliases": aliases})
        elif action == "set":
            if not address or not name:
                formatter.print_error("Usage: config alias set <address> <name>")
                return
            config.set_alias(address, name)
            formatter.print_success(f"Set alias '{name}' for {address}")
        elif action == "remove":
            if not name:
                formatter.print_error("Usage: config alias remove <name>")
                return
            if config.remove_alias(name):
                formatter.print_success(f"Removed alias '{name}'")
            else:
                formatter.print_error(f"Alias not found: {name}")
        else:
            formatter.print_error(f"Unknown action: {action}")
    except Exception as e:
        formatter.print_error(str(e))


@app.command("preset")
def config_preset(
    action: str = typer.Argument(..., help="Action: list, get, set, remove"),
    name: Optional[str] = typer.Argument(None, help="Preset name"),
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
    service: Optional[str] = typer.Option(None, "--service", "-s", help="Service UUID"),
    char: Optional[str] = typer.Option(None, "--char", "-c", help="Characteristic UUID"),
) -> None:
    """Manage GATT presets."""
    formatter = OutputFormatter(json_output=not human)
    
    try:
        from airctl.config.manager import ConfigManager
        
        config = ConfigManager()
        
        if action == "list":
            presets = config.list_presets()
            formatter.print({"presets": presets})
        elif action == "get":
            if not name:
                formatter.print_error("Usage: config preset get <name>")
                return
            preset = config.get_preset(name)
            if preset:
                formatter.print({"name": name, "preset": preset})
            else:
                formatter.print_error(f"Preset not found: {name}")
        elif action == "set":
            if not name:
                formatter.print_error("Usage: config preset set <name> --service UUID [--char UUID]")
                return
            preset_config = {}
            if service:
                preset_config["service"] = service
            if char:
                preset_config["char"] = char
            if preset_config:
                config.set_preset(name, preset_config)
                formatter.print_success(f"Set preset '{name}'")
            else:
                formatter.print_error("No preset configuration provided")
        elif action == "remove":
            if not name:
                formatter.print_error("Usage: config preset remove <name>")
                return
            if config.remove_preset(name):
                formatter.print_success(f"Removed preset '{name}'")
            else:
                formatter.print_error(f"Preset not found: {name}")
        else:
            formatter.print_error(f"Unknown action: {action}")
    except Exception as e:
        formatter.print_error(str(e))


@app.command("reset")
def config_reset(
    human: bool = typer.Option(False, "-h", "--human", help="Human-readable output (default: JSON)"),
    confirm: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"),
) -> None:
    """Reset configuration to defaults."""
    formatter = OutputFormatter(json_output=not human)
    
    if not confirm:
        if not typer.confirm("This will reset all configuration. Continue?"):
            formatter.print("Cancelled")
            return
    
    try:
        from airctl.config.manager import ConfigManager
        
        config = ConfigManager()
        config.reset()
        formatter.print_success("Configuration reset to defaults")
    except Exception as e:
        formatter.print_error(str(e))
