"""Configuration commands: config get, config set, config show."""

import click

from mcpbundles.config import (
    CONFIG_FILE,
    config_with_defaults,
    load_config,
    save_config,
)
from mcpbundles.output import render_success, render_error, print_json, stdout_console


@click.group("config")
def config_group() -> None:
    """Manage CLI configuration."""
    pass


@config_group.command("show")
@click.option("--json", "as_json", is_flag=True, help="Output as JSON")
def config_show(as_json: bool) -> None:
    """Show all configuration values."""
    cfg = config_with_defaults()
    if as_json:
        print_json(cfg)
    else:
        from rich.panel import Panel
        lines = [f"  [bold]{k}:[/bold] {v}" for k, v in sorted(cfg.items())]
        stdout_console.print(Panel("\n".join(lines), title="Configuration", border_style="blue", padding=(1, 2)))
        stdout_console.print(f"  [dim]Config file: {CONFIG_FILE}[/]")


@config_group.command("get")
@click.argument("key")
def config_get(key: str) -> None:
    """Get a configuration value."""
    cfg = config_with_defaults()
    if key in cfg:
        print(cfg[key])
    else:
        render_error(f"Unknown config key: {key}")
        stdout_console.print(f"  Available keys: {', '.join(sorted(cfg.keys()))}")
        raise SystemExit(1)


@config_group.command("set")
@click.argument("key")
@click.argument("value")
def config_set(key: str, value: str) -> None:
    """Set a configuration value."""
    cfg = load_config()

    if value.lower() == "true":
        cfg[key] = True
    elif value.lower() == "false":
        cfg[key] = False
    else:
        try:
            cfg[key] = int(value)
        except ValueError:
            cfg[key] = value

    save_config(cfg)
    render_success(f"{key} = {cfg[key]}")


@config_group.command("reset")
def config_reset() -> None:
    """Reset configuration to defaults."""
    if CONFIG_FILE.exists():
        CONFIG_FILE.unlink()
    render_success("Configuration reset to defaults.")
