"""
Module: config_cmd
Description: Configuration management commands

Implements:
    - docs/cli/reference.md#huitzo-config
"""

from typing import Any

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

from huitzo_cli.config import ConfigManager

console = Console()
config_app = typer.Typer(help="Manage configuration")


@config_app.callback(invoke_without_command=True)
def config_callback(ctx: typer.Context) -> None:
    """Manage configuration - get, set, list, and view config files."""
    if ctx.invoked_subcommand is None:
        console.print(ctx.get_help())
        raise typer.Exit(0)


@config_app.command()
def get(key: str) -> None:
    """Get configuration value.

    Args:
        key: Configuration key (e.g., 'api_url' or 'auth.token')
    """
    config = ConfigManager()
    value = config.get(key)

    if value is None:
        console.print(f"[yellow]⚠️  {key} not set[/yellow]")
        raise typer.Exit(1)

    console.print(f"{key} = {value}")


@config_app.command()
def set(
    key: str,
    value: str,
    scope: str = typer.Option("user", "--scope", help="Config scope (user or project)"),
) -> None:
    """Set configuration value.

    Args:
        key: Configuration key (e.g., 'auth.token')
        value: Value to set
    """
    config = ConfigManager()

    try:
        config.set(key, value, scope=scope)
        console.print(f"[green]✅ {key} set to {value}[/green]")
    except Exception as e:
        console.print(f"[red]❌ Failed to set {key}: {e}[/red]")
        raise typer.Exit(1)


@config_app.command()
def list_config() -> None:
    """List all configuration values."""
    config = ConfigManager()
    config_dict = config.to_dict()

    table = Table(title="Configuration")
    table.add_column("Key", style="cyan")
    table.add_column("Value", style="green")

    def flatten_dict(d: dict[str, Any], parent_key: str = "") -> list[tuple[str, str]]:
        items = []
        for k, v in d.items():
            new_key = f"{parent_key}.{k}" if parent_key else k
            if isinstance(v, dict):
                items.extend(flatten_dict(v, new_key))
            else:
                items.append((new_key, str(v)))
        return items

    for key, value in flatten_dict(config_dict):
        table.add_row(key, value)

    console.print(table)


@config_app.command()
def path(
    scope: str = typer.Option("user", "--scope", help="Config scope (user or project)"),
) -> None:
    """Show configuration file path.

    Args:
        scope: Config scope (user or project)
    """
    config = ConfigManager()
    config_path = config.get_config_path(scope=scope)
    console.print(f"[cyan]{scope.capitalize()} config:[/cyan] {config_path}")
    console.print(f"[yellow]Exists:[/yellow] {config_path.exists()}")
