"""Config commands — set, get, list, use-account."""

from __future__ import annotations

import typer

from turumba_cli.config import load_config, set_value
from turumba_cli.output import console, render_json, success

app = typer.Typer(name="config", help="Manage CLI configuration.")


@app.command("set")
def config_set(
    key: str = typer.Argument(help="Config key (e.g., gateway_url, default_output)"),
    value: str = typer.Argument(help="Config value"),
) -> None:
    """Set a configuration value."""
    set_value(key, value)
    success(f"{key} = {value}")


@app.command("get")
def config_get(
    key: str = typer.Argument(help="Config key to read"),
    output: str = typer.Option("table", "--output", "-o", help="Output format"),
) -> None:
    """Get a configuration value."""
    config = load_config()
    value = config.get(key)
    if output == "json":
        render_json({key: value})
    elif value is None:
        console.print(f"{key}: [dim]not set[/dim]")
    else:
        console.print(f"{key}: {value}")


@app.command("list")
def config_list(
    output: str = typer.Option("table", "--output", "-o", help="Output format"),
) -> None:
    """List all configuration values."""
    config = load_config()
    if output == "json":
        render_json(config)
        return

    console.print("\n[bold]Turumba CLI Configuration[/bold]\n")
    for key, value in config.items():
        if value is None:
            console.print(f"  [bold]{key}[/bold]: [dim]not set[/dim]")
        else:
            console.print(f"  [bold]{key}[/bold]: {value}")
    console.print()


@app.command("use-account")
def use_account(
    account_id: str = typer.Argument(help="Account ID to use as default"),
) -> None:
    """Set the default account for subsequent commands."""
    set_value("default_account_id", account_id)
    success(f"Default account set to: {account_id}")
