"""appxen login — configure API key and endpoint."""

from __future__ import annotations

import typer
from rich.prompt import Prompt

from appxen_cli.client import AppXenClient
from appxen_cli.config import DEFAULT_ENDPOINT, save_profile
from appxen_cli.display import console, error, success, warn


def login(
    profile: str = typer.Option("default", "--profile", "-p", help="Profile name"),
    endpoint: str = typer.Option(DEFAULT_ENDPOINT, "--endpoint", "-e", help="Gateway API endpoint"),
) -> None:
    """Configure your AppXen API key."""
    api_key = Prompt.ask("API key", password=True, console=console)

    if not api_key:
        error("API key cannot be empty.")
        raise typer.Exit(1)

    if not api_key.startswith("axgw_"):
        error("Invalid API key format. Keys start with 'axgw_'.")
        raise typer.Exit(1)

    # Validate key with an authenticated request
    try:
        with AppXenClient(api_key=api_key, endpoint=endpoint) as client:
            client.stats()  # authenticated endpoint — verifies key works
        success("API key validated.")
    except Exception:
        # Health check (unauthenticated) to distinguish bad key vs unreachable
        try:
            with AppXenClient(api_key=api_key, endpoint=endpoint) as client:
                client.health()
            warn("Gateway reachable but API key could not be verified. Saving anyway.")
        except Exception:
            warn("Could not reach the gateway. Key saved but not verified.")

    # Quick orchestrator health check (silent — not all tenants have it)
    try:
        with AppXenClient(api_key=api_key, endpoint=endpoint) as client:
            client.orchestrator_health()
        success("Orchestrator reachable via gateway.")
    except Exception:
        pass  # Silent — orchestrator may not be enabled for all tenants

    save_profile(
        api_key=api_key,
        endpoint=endpoint,
        profile=profile,
    )
    success(f"Saved to profile [bold]{profile}[/bold].")

    # Check for updates (non-blocking, errors silently ignored)
    from appxen_cli.version_check import is_update_available
    from appxen_cli import __version__

    available, latest = is_update_available()
    if available:
        console.print()
        console.print(
            f"[yellow]Update available:[/yellow] {__version__} → {latest}"
        )
        console.print("Run [bold]appxen update[/bold] to upgrade.")
