"""Authentication command for gjalla-precommit."""

from __future__ import annotations

import click

from ..config.settings import Settings
from ..display.output import console, success, error, info


@click.command()
@click.option("--key", help="API key to save")
def auth(key: str | None = None) -> None:
    """Authenticate with Gjalla API.

    If --key is provided, saves it to the config file.
    Otherwise, prompts for the key interactively.
    """
    if key is None:
        key = click.prompt("Enter your Gjalla API key", hide_input=True)

    if not key:
        error("API key cannot be empty")
        raise SystemExit(1)

    # Load existing settings and update
    settings = Settings.load()
    settings = settings.model_copy(update={"api_key": key})
    settings.save()

    # Mask key for display
    masked = key[:4] + "..." + key[-4:] if len(key) > 8 else "****"
    success(f"API key saved: {masked}")
