"""Configuration commands."""

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

from iseq_flow.config import get_settings, load_config, save_config

console = Console()


@click.group()
def config():
    """Configuration management."""
    pass


@config.command("show")
def show_config():
    """Show current configuration."""
    settings = get_settings()
    file_config = load_config()

    table = Table(show_header=True, header_style="bold")
    table.add_column("Setting")
    table.add_column("Value")
    table.add_column("Source")

    # Show key settings
    config_items = [
        ("api_url", settings.api_url),
        ("zitadel_issuer", settings.zitadel_issuer),
        ("zitadel_client_id", settings.zitadel_client_id),
    ]

    for key, value in config_items:
        source = "[green]config file[/green]" if key in file_config else "[dim]default[/dim]"
        table.add_row(key, value, source)

    console.print(table)


@config.command("set")
@click.argument("key")
@click.argument("value")
def set_config(key: str, value: str):
    """Set a configuration value."""
    valid_keys = ["api_url", "zitadel_issuer", "zitadel_client_id"]

    if key not in valid_keys:
        console.print(f"[red]Invalid key:[/red] {key}")
        console.print(f"Valid keys: {', '.join(valid_keys)}")
        raise SystemExit(1)

    file_config = load_config()
    file_config[key] = value
    save_config(file_config)

    console.print(f"[green]Set {key}=[/green]{value}")


@config.command("reset")
def reset_config():
    """Reset configuration to defaults."""
    save_config({})
    console.print("[green]Configuration reset to defaults.[/green]")
