"""
Module: auth_command
Description: Login and logout commands

Implements:
    - docs/cli/reference.md#huitzo-login
    - docs/guides/developer-environment.md#authentication
"""

from __future__ import annotations

import typer
from rich.console import Console

from huitzo_cli.auth import AuthClient
from huitzo_cli.config import ConfigManager

console = Console()
auth_app = typer.Typer(help="Authentication commands", invoke_without_command=True)


@auth_app.command()
def login(
    url: str | None = typer.Option(
        None,
        "--url",
        help="Backend API URL (e.g., http://localhost:8000)",
    ),
    email: str | None = typer.Option(
        None,
        "--email",
        help="Account email address",
    ),
    password: str | None = typer.Option(
        None,
        "--password",
        help="Account password (will prompt if not provided)",
    ),
    token: str | None = typer.Option(
        None,
        "--token",
        help="Pre-existing auth token (for testing)",
    ),
) -> None:
    """Login to Huitzo backend.

    Authenticates against the backend API and stores the access token.
    """
    config = ConfigManager()
    auth_client = AuthClient(config)

    # Direct token mode (for testing)
    if token:
        try:
            auth_client.login(email=email or "", token=token)
            console.print("[green]Logged in with token[/green]")
            return
        except RuntimeError as e:
            console.print(f"[red]Login failed: {e}[/red]")
            raise typer.Exit(1)

    # Prompt for missing fields
    if not email:
        email = typer.prompt("Email")

    if not password:
        password = typer.prompt("Password", hide_input=True)

    try:
        data = auth_client.login(email=email, password=password, url=url)
        user_email = data.get("email", email)
        console.print(f"[green]Logged in as {user_email}[/green]")
        if url:
            console.print(f"API URL: {url}")
    except RuntimeError as e:
        console.print(f"[red]Login failed: {e}[/red]")
        raise typer.Exit(1)


@auth_app.command()
def logout() -> None:
    """Logout from Huitzo backend."""
    config = ConfigManager()
    auth_client = AuthClient(config)

    try:
        auth_client.logout()
        console.print("[green]Logged out successfully[/green]")
    except OSError as e:
        console.print(f"[red]Logout failed: {e}[/red]")
        raise typer.Exit(1)
