"""Login command implementation."""

import typer

from cli.infrastructure.auth_storage import save_credentials
from cli.infrastructure.command import async_command
from cli.infrastructure.config import get_api_url
from cli.infrastructure.console import Confirm, Prompt, Text
from cli.infrastructure.output import OutputService
from cli.infrastructure.provider_setup import prompt_provider_credentials
from cli.infrastructure.spinner import spinner
from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.dtos.auth import LoginRequest


def login_command(
    email: str | None = typer.Option(None, "-e", "--email", help="Email address"),
    password: str | None = typer.Option(
        None, "--password", help="Password (avoid: exposes in shell history)"
    ),
) -> None:
    """Login and save API key.

    First-time users will be prompted to set up provider credentials.

    Examples:

        alloy login
        alloy login -e user@example.com
    """
    _execute_login(email, password)


@async_command
async def _execute_login(
    email: str | None,
    password: str | None,
) -> None:
    """Execute the login operation.

    Args:
        email: Optional email (will prompt if not provided)
        password: Optional password (will prompt if not provided)
    """
    output = OutputService.get()
    api_url = get_api_url()

    # Prompt for credentials if not provided
    if not email:
        email = Prompt.ask(Text("Email"))

    if not password:
        password = Prompt.ask(Text("Password"), password=True)

    async with spinner("Authenticating..."):
        async with ApiClient(base_url=api_url, api_key="") as client:
            response = await client.login(LoginRequest(email=email, password=password))

    # Save credentials
    save_credentials(api_url, response.api_key)

    output.result(
        action="login",
        resource="session",
        identifier=str(response.user_id),
        name=response.email,
        extra_fields={
            "Name": response.name,
            "Organization ID": str(response.organization_id),
            "Credentials Saved": "~/.alloy-runtime/config",
        },
    )

    if response.is_new_user:
        if Confirm.ask(
            Text("Would you like to set up AI provider credentials now?"),
            default=True,
        ):
            await prompt_provider_credentials(api_url, response.api_key)
        else:
            output.result(
                action="setup",
                resource="provider_credentials",
                status="pending",
                identifier=None,
                name=None,
                extra_fields={
                    "Next Step": "alloy credentials update <credential-id> --value <api-key>"
                },
            )
