"""Login command - authenticate with an API key."""

import httpx
import typer
from rich.prompt import Prompt

from nogic.config import Config, is_dev_mode, get_api_url
from nogic import telemetry, ui


def login():
    """Authenticate with your Nogic account using an API key."""
    if is_dev_mode():
        ui.dev_banner(get_api_url())

    ui.console.print()
    ui.info("Enter your API key to authenticate.")
    ui.dim("  Create one at nogic.dev/dashboard")
    ui.console.print()

    api_key = Prompt.ask("  API key", console=ui.console, password=True)
    api_key = api_key.strip()

    if not api_key.startswith("sk_"):
        ui.console.print()
        ui.error("Invalid API key. Keys start with 'sk_'.")
        raise typer.Exit(1)

    # Verify the key works (lightweight auth check)
    base_url = get_api_url()
    with ui.status_spinner("Verifying key..."):
        try:
            resp = httpx.get(
                f"{base_url}/v1/projects",
                headers={"Authorization": f"Bearer {api_key}"},
                timeout=10.0,
            )
            if resp.status_code == 401:
                ui.console.print()
                ui.error("Invalid or revoked API key.")
                telemetry.capture("cli_login", {"success": False, "error": "invalid_key"})
                raise typer.Exit(1)
            elif not resp.is_success:
                resp.raise_for_status()
        except httpx.RequestError:
            ui.console.print()
            ui.warn("Could not reach the server to verify. Saving key anyway.")

    config = Config.load()
    config.api_key = api_key
    config.save_global()

    ui.console.print()
    ui.success("Logged in successfully.")
    ui.dim("  API key saved to ~/.nogic/config.json")
    ui.console.print()
    ui.dim("  Next: run `nogic init` in a project directory.")

    telemetry.capture("cli_login", {"success": True, "method": "api_key"})
