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

import webbrowser
from typing import Annotated, Optional

import httpx
import typer

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

DASHBOARD_URL = "https://www.nogic.dev/dashboard"


def login(
    api_key: Annotated[Optional[str], typer.Option(
        "--api-key", "-k",
        envvar="NOGIC_API_KEY",
        help="API key (will prompt if not provided).",
    )] = None,
):
    """Authenticate with your Nogic API key."""
    if is_dev_mode():
        ui.dev_banner(get_api_url())

    if not api_key:
        ui.console.print()
        ui.info("Get your API key from the Nogic dashboard.")
        ui.console.print()

        try:
            webbrowser.open(DASHBOARD_URL)
            ui.dim(f"  Opened {DASHBOARD_URL}")
        except Exception:
            ui.dim(f"  Visit: {DASHBOARD_URL}")

        ui.console.print()
        api_key = typer.prompt("Paste your API key", hide_input=True)

    api_key = api_key.strip()
    if not api_key:
        ui.error("No API key provided.")
        raise typer.Exit(1)

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

    client = NogicClient(config)
    try:
        with ui.status_spinner("Verifying..."):
            user_info = client.verify_key()

        ui.console.print()
        ui.success(f"Logged in as {user_info['user_id'][:8]}...")
        config.save_global()
        ui.dim("  API key saved. You're ready to go.")
        ui.console.print()
        ui.dim("  Next: run `nogic init` in a project directory.")

        telemetry.capture("cli_login", {"success": True})
        telemetry.identify(user_info.get("user_id"))

    except httpx.HTTPStatusError as e:
        telemetry.capture("cli_login", {"success": False, "error": e.response.status_code})
        if e.response.status_code == 401:
            ui.error("Invalid API key. Please check and try again.")
        else:
            ui.error(f"Authentication failed ({e.response.status_code})")
        raise typer.Exit(1)
    except httpx.RequestError:
        ui.error("Connection failed. Check your network and try again.")
        raise typer.Exit(1)
    finally:
        client.close()
