"""gsearch config — view and modify configuration."""

from __future__ import annotations

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

from gsearch_mcp_cli.config import DEFAULTS, Config
from gsearch_mcp_cli.exceptions import ConfigError

console = Console()


@click.group("config")
def config_cmd() -> None:
    """View and modify gsearch configuration."""


@config_cmd.command("show")
def config_show() -> None:
    """Print all configuration values."""
    cfg = Config()
    data = cfg.show()

    table = Table(title="gsearch configuration")
    table.add_column("Key", style="cyan", no_wrap=True)
    table.add_column("Value", style="green")
    table.add_column("Default", style="dim")

    for key in sorted(data):
        current = data[key]
        default = DEFAULTS.get(key)
        style = "" if current == default else "bold yellow"
        table.add_row(key, str(current), str(default), style=style)

    console.print(table)


@config_cmd.command("get")
@click.argument("key")
def config_get(key: str) -> None:
    """Get a single configuration value."""
    cfg = Config()
    try:
        value = cfg.get(key)
        console.print(f"[cyan]{key}[/] = [green]{value}[/]")
    except ConfigError as exc:
        console.print(f"[bold red]Error:[/] {exc}")
        raise SystemExit(1)


@config_cmd.command("set")
@click.argument("key")
@click.argument("value")
def config_set(key: str, value: str) -> None:
    """Set a configuration value."""
    cfg = Config()
    try:
        cfg.set(key, value)
        console.print(f"[green]✓[/] Set [cyan]{key}[/] = [green]{cfg.get(key)}[/]")
    except ConfigError as exc:
        console.print(f"[bold red]Error:[/] {exc}")
        raise SystemExit(1)
