"""API key management commands."""

import platform

import typer

from nogic.config import Config, is_dev_mode, get_api_url
from nogic.api.client import NogicClient
from nogic import telemetry, ui

keys_app = typer.Typer(no_args_is_help=True)


def _require_auth() -> tuple[Config, NogicClient]:
    config = Config.load()
    if not config.api_key:
        ui.error("Not logged in. Run `nogic login` first.")
        raise typer.Exit(1)
    return config, NogicClient(config)


@keys_app.callback()
def keys_callback():
    """Manage API keys for MCP clients."""
    if is_dev_mode():
        ui.dev_banner(get_api_url())


@keys_app.command()
def show(
    reveal: bool = typer.Option(False, "--reveal", "-r", help="Show the full API key."),
):
    """Show your current MCP API key."""
    config = Config.load()
    if config.api_key:
        ui.console.print()
        ui.info("Your MCP API key:")
        if reveal:
            ui.console.print(f"\n  [bold]{config.api_key}[/]\n")
        else:
            ui.console.print(f"\n  [bold]{config.api_key[:12]}...[/]\n")
            ui.dim("  Use --reveal to show the full key.")
        ui.dim("  Use as a Bearer token in MCP client configs (Claude Desktop, Cursor, etc.).")
    else:
        ui.console.print()
        ui.warn("No API key saved locally. Run `nogic keys create` to create one.")


@keys_app.command("list")
def list_keys():
    """List all your API keys."""
    config, client = _require_auth()

    try:
        with ui.status_spinner("Fetching keys..."):
            keys = client.list_api_keys()
    except Exception as e:
        ui.error(f"Failed to list keys: {e}")
        raise typer.Exit(1)
    finally:
        client.close()

    if not keys:
        ui.console.print()
        ui.info("No API keys found. Run `nogic keys create` to create one.")
        return

    ui.console.print()
    ui.info(f"{len(keys)} API key(s):")
    ui.console.print()
    for k in keys:
        status = "[green]active[/]" if k["is_active"] else "[red]revoked[/]"
        last_used = k.get("last_used_at") or "never"
        ui.console.print(f"  [bold]{k['key_prefix']}...[/]  {k['name']}  {status}  (last used: {last_used})")
        ui.dim(f"    ID: {k['id']}")


@keys_app.command()
def create(
    name: str = typer.Option(None, "--name", "-n", help="Key name (default: CLI Login — hostname)"),
):
    """Create a new API key."""
    config, client = _require_auth()
    key_name = name or f"CLI Login — {platform.node()}"

    try:
        with ui.status_spinner("Creating key..."):
            result = client.create_api_key(key_name)
    except Exception as e:
        ui.error(f"Failed to create key: {e}")
        raise typer.Exit(1)
    finally:
        client.close()

    config.api_key = result["key"]
    config.save_global()

    ui.console.print()
    ui.success(f"API key created: {result['name']}")
    ui.console.print(f"\n  [bold]{result['key']}[/]\n")
    ui.dim("  Saved to ~/.nogic/config.json")
    ui.dim("  Use as a Bearer token in MCP client configs (Claude Desktop, Cursor, etc.).")

    telemetry.capture("cli_keys_create", {"success": True})


@keys_app.command()
def revoke(
    key_id: str = typer.Argument(help="Key ID to revoke"),
):
    """Revoke an API key."""
    config, client = _require_auth()

    try:
        client.revoke_api_key(key_id)
    except Exception as e:
        ui.error(f"Failed to revoke key: {e}")
        raise typer.Exit(1)
    finally:
        client.close()

    ui.console.print()
    ui.success(f"API key {key_id} revoked.")
    telemetry.capture("cli_keys_revoke", {"success": True})
