"""Authentication commands: login, logout, whoami."""

import click

from mcpbundles.auth import oauth_flow
from mcpbundles.config import CLISettings, load_token, delete_token, save_token
from mcpbundles.daemon import get_pid_file
from mcpbundles.output import render_success, render_error, render_warning, print_json


@click.command()
@click.option("--api-key", envvar="MCPBUNDLES_API_KEY", help="Authenticate with an API key instead of OAuth")
@click.pass_context
def login(ctx: click.Context, api_key: str | None) -> None:
    """Authenticate with MCPBundles."""
    if api_key:
        save_token({"access_token": api_key, "auth_type": "api_key"})
        render_success("Authenticated with API key!")
        return

    settings: CLISettings = ctx.obj["settings"]
    try:
        oauth_flow(oauth_base_url=settings.oauth_base_url)
        render_success("Authenticated with OAuth!")
    except Exception as e:
        render_error(f"Authentication failed: {e}")
        raise SystemExit(1)


@click.command()
def logout() -> None:
    """Remove stored credentials and stop running services."""
    pid_file = get_pid_file()
    if pid_file.exists():
        render_warning("Stopping tunnel daemon first...")
        from mcpbundles.daemon import stop_daemon
        stop_daemon()

    from mcpbundles.connections import ConnectionManager
    mgr = ConnectionManager()
    count = mgr.remove_all()

    delete_token()
    render_success(f"Logged out. Removed {count} saved connection(s).")


@click.command()
@click.option("--json", "as_json", is_flag=True, help="Output as JSON")
@click.pass_context
def whoami(ctx: click.Context, as_json: bool) -> None:
    """Show current auth status and connected user."""
    token_data = load_token()
    if not token_data:
        render_error("Not authenticated. Run 'mcpbundles login' first.")
        raise SystemExit(1)

    settings: CLISettings = ctx.obj["settings"]
    auth_type = token_data.get("auth_type", "oauth")

    info = {
        "auth_type": auth_type,
        "server": settings.base_url,
        "config_dir": str(settings.config_dir),
    }

    if as_json:
        print_json(info)
    else:
        from rich.panel import Panel
        from mcpbundles.output import stdout_console

        lines = [
            f"  [bold]Auth type:[/bold]  {auth_type}",
            f"  [bold]Server:[/bold]     {settings.base_url}",
            f"  [bold]Config:[/bold]     {settings.config_dir}",
        ]
        stdout_console.print(Panel("\n".join(lines), title="MCPBundles Identity", border_style="green", padding=(1, 2)))
