"""ievo config — manage global settings and encrypted credentials."""

from __future__ import annotations

import typer

from ievo.core.config import ensure_home
from ievo.core.credentials import (
    delete_credential,
    get_credential,
    is_sensitive_key,
    list_credentials,
    set_credential,
)
from ievo.core.global_config import get_config, load_global_config, set_config
from ievo.utils.console import error, info, step, success, warn

app = typer.Typer(no_args_is_help=True)


@app.command("set")
def config_set(
    key: str = typer.Argument(help="Config key (e.g. ANTHROPIC_API_KEY, default_model)"),
    value: str = typer.Argument(help="Value to set"),
) -> None:
    """Set a config value. Sensitive keys are encrypted automatically."""
    home = ensure_home()

    if is_sensitive_key(key):
        set_credential(home, key, value)
        success(f"[bold]{key}[/bold] saved (encrypted)")
    else:
        set_config(home, key, value)
        success(f"[bold]{key}[/bold] = {value}")


@app.command("get")
def config_get(
    key: str = typer.Argument(help="Config key to retrieve"),
) -> None:
    """Get a config value. Decrypts credentials automatically."""
    home = ensure_home()

    if is_sensitive_key(key):
        val = get_credential(home, key)
        if val is None:
            error(f"[bold]{key}[/bold] not found")
            raise typer.Exit(1)
        # Mask all but last 4 chars
        masked = "•" * max(0, len(val) - 4) + val[-4:]
        info(f"[bold]{key}[/bold] = {masked}")
    else:
        val = get_config(home, key)
        if val is None:
            error(f"[bold]{key}[/bold] not found")
            raise typer.Exit(1)
        info(f"[bold]{key}[/bold] = {val}")


@app.command("list")
def config_list() -> None:
    """List all config keys and credential names."""
    home = ensure_home()

    config = load_global_config(home)
    cred_keys = list_credentials(home)

    if config:
        info("[bold]Config[/bold] (plaintext)")
        for k, v in config.items():
            step(f"{k} = {v}")

    if cred_keys:
        info("[bold]Credentials[/bold] (encrypted)")
        for k in cred_keys:
            step(f"{k} = •••")

    if not config and not cred_keys:
        warn("No configuration found. Run [bold]ievo init[/bold] first.")


@app.command("delete")
def config_delete(
    key: str = typer.Argument(help="Config key to delete"),
) -> None:
    """Delete a config key or credential."""
    home = ensure_home()

    if is_sensitive_key(key):
        if delete_credential(home, key):
            success(f"[bold]{key}[/bold] deleted")
        else:
            error(f"[bold]{key}[/bold] not found")
            raise typer.Exit(1)
    else:
        config = load_global_config(home)
        if key not in config:
            error(f"[bold]{key}[/bold] not found")
            raise typer.Exit(1)
        del config[key]
        from ievo.core.global_config import save_global_config

        save_global_config(home, config)
        success(f"[bold]{key}[/bold] deleted")
