"""
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 logging
import os

import typer
from rich.console import Console

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

console = Console()
logger = logging.getLogger(__name__)


def _remove_stale_config_token(config: ConfigManager) -> None:
    """Remove any leftover ``auth.token`` from config.yaml.

    Tokens are stored exclusively in TokenStore (~/.huitzo/token).  Old
    config.yaml entries cause confusing output from ``huitzo config get``.
    """
    import yaml

    config_path = config.get_config_path(scope="user")
    if not config_path.exists():
        return
    try:
        with open(config_path) as f:
            data = yaml.safe_load(f) or {}
        auth_section = data.get("auth")
        if isinstance(auth_section, dict) and "token" in auth_section:
            del auth_section["token"]
            if os.name != "nt":
                fd = os.open(str(config_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
                with os.fdopen(fd, "w") as f:
                    yaml.dump(data, f, default_flow_style=False)
            else:
                with open(config_path, "w") as f:
                    yaml.dump(data, f, default_flow_style=False)
    except (OSError, yaml.YAMLError):
        pass  # best-effort cleanup


def login(
    url: str | None = typer.Option(
        None,
        "--url",
        help="Override API URL (default: https://huitzo.ai)",
    ),
    email: str | None = typer.Option(
        None,
        "--email",
        help="Account email address",
    ),
) -> None:
    """Login to Huitzo backend.

    Authenticates against the backend API and stores the access token.
    Use the HUITZO_AUTH_TOKEN env var to provide a pre-existing token
    instead of credential-based login.
    """
    config = ConfigManager()
    auth_client = AuthClient(config)

    # Env var token mode (replaces the old --token flag)
    env_token = os.environ.get("HUITZO_AUTH_TOKEN")
    if env_token:
        try:
            auth_client.login(email=email or "", token=env_token)
            _remove_stale_config_token(config)
            console.print("[green]Logged in with token from HUITZO_AUTH_TOKEN[/green]")
            return
        except RuntimeError as e:
            logger.debug("Login failed (token mode): %s", e)
            console.print("[red]Login failed: invalid or expired token[/red]")
            raise typer.Exit(1)

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

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

    try:
        data = auth_client.login(email=email, password=password, url=url)
        _remove_stale_config_token(config)
        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:
        logger.debug("Login failed: %s", e)
        console.print("[red]Login failed: check your credentials and try again[/red]")
        raise typer.Exit(1)


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)
