"""Keiro admin command — persistent toggle for admin metrics.

Stores the setting in ``~/.keiro/credentials``. Once enabled, all
keiro commands automatically display the admin metrics panel.

Usage::

    keiro admin           # toggle admin mode on/off
    keiro admin --status  # show current state without changing it
"""

from __future__ import annotations

import argparse

from rich.console import Console


def _on_off_label(is_on: bool) -> str:
    """Rich markup for an on/off state indicator."""
    return "[bold]on[/bold]" if is_on else "[dim]off[/dim]"


def build_parser() -> argparse.ArgumentParser:
    """Build the argument parser for ``keiro admin``."""
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument(
        "--status",
        action="store_true",
        help="Show current admin mode state without changing it.",
    )
    parser.add_argument(
        "--reset",
        action="store_true",
        help="Clear the saved admin token and disable admin mode.",
    )
    return parser


def run(args: argparse.Namespace) -> int:
    """Toggle admin mode or show status."""
    from keiro.credentials import (
        clear_admin_token,
        is_admin_mode,
        load_credentials,
        set_admin_mode,
    )

    currently_on = is_admin_mode()
    has_token = bool(load_credentials().get("admin_token"))
    console = Console()

    if args.status:
        from keiro.cli.setup import _mask_key

        token_cred = load_credentials().get("admin_token", "")
        if token_cred:
            token_label = f"{_mask_key(token_cred)} [dim](deprecated)[/dim]"
        else:
            token_label = "not configured (using API key role)"
        console.print(f"  Admin mode:  {_on_off_label(currently_on)}")
        console.print(f"  Admin token: {token_label}")
        return 0

    if args.reset:
        clear_admin_token()
        set_admin_mode(False)
        has_token = False
        console.print("  [dim]Admin token cleared.[/dim]")
        console.print()

    # Toggle admin mode (display-only). No token required — admin access
    # is now determined by the API key role segment.
    from keiro.cli.animations import toggle_switch

    new_state = toggle_switch("Admin mode", currently_on)
    if new_state != currently_on:
        set_admin_mode(new_state)
        _print_transition(console, currently_on, new_state)
    else:
        console.print(f"  Admin mode  {_on_off_label(currently_on)} [dim](unchanged)[/dim]")
        console.print()

    if new_state and not has_token:
        console.print(
            "  [dim]Admin access depends on your API key role.[/dim]",
        )
        console.print()
    elif new_state and has_token:
        from keiro.cli.setup import _mask_key

        token_cred = load_credentials().get("admin_token", "")
        if token_cred:
            masked = _mask_key(token_cred)
            console.print(
                f"  [dim]Token: {masked}"
                f"  (deprecated, reset with keiro admin --reset)[/dim]",
            )
            console.print()
    return 0


def _print_transition(
    console: Console,
    was_on: bool,
    now_on: bool,
) -> None:
    """Print the on/off transition line with usage guidance."""
    prev = _on_off_label(was_on)
    curr = _on_off_label(now_on)
    console.print(f"  Admin mode  {prev} → {curr}")
    console.print()
    if now_on:
        console.print("  [dim]Metrics panel will show on every request.[/dim]")
        console.print(
            "  [dim]Toggle in REPL with /admin,"
            " or run[/dim] keiro admin [dim]again.[/dim]",
        )
    else:
        console.print("  [dim]Re-enable anytime with[/dim] keiro admin")
    console.print()
