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

from __future__ import annotations

import typer
from rich.prompt import Prompt

from appxen_cli.client import AppXenClient, OrchestratorClient
from appxen_cli.config import (
    DEFAULT_ENDPOINT,
    DEFAULT_ORCHESTRATOR_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"),
    orchestrator_url: str = typer.Option(
        DEFAULT_ORCHESTRATOR_ENDPOINT,
        "--orchestrator-url",
        help="Orchestrator API endpoint",
    ),
    tenant_id: str = typer.Option("", "--tenant-id", "-t", help="Tenant ID for orchestrator"),
) -> None:
    """Configure your AppXen API key and orchestrator settings."""
    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.")

    # Validate orchestrator connectivity if tenant_id provided
    if tenant_id and orchestrator_url:
        try:
            with OrchestratorClient(endpoint=orchestrator_url, tenant_id=tenant_id) as client:
                client.health()
            success("Orchestrator reachable.")
        except Exception:
            warn("Could not reach the orchestrator. Settings saved but not verified.")

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