"""Login command - Authenticate with Claude Code.

Contract: CNT-T4-CMD-005
Traceability: UX-003
"""

import subprocess
import sys

import click

from laida_cli.ui import LaidaConsole

console = LaidaConsole()


@click.command("login")
@click.option(
    "--check",
    is_flag=True,
    help="Only check if already authenticated (don't open login)",
)
def login_command(check: bool) -> None:
    """Authenticate with Claude Code.

    Opens Claude Code interactive mode to complete authentication.
    Use --check to verify current authentication status.

    Examples:
        laida login         # Start authentication
        laida login --check # Check if authenticated
    """
    if check:
        _check_auth_status()
        return

    console.print()
    console.header("Claude Code Authentication")
    console.print()
    console.muted("Opening Claude Code for authentication...")
    console.muted("Complete the login process in the terminal.")
    console.print()

    try:
        # Open claude in interactive mode for login
        # This will handle the OAuth flow or API key setup
        result = subprocess.run(
            ["claude"],
            stdin=sys.stdin,
            stdout=sys.stdout,
            stderr=sys.stderr,
            check=False,
        )

        console.print()
        if result.returncode == 0:
            console.success("Authentication completed!")
            console.hint("You can now run: laida run 0 0")
        else:
            console.warning("Authentication may not have completed.")
            console.hint("Try running 'claude' directly if issues persist.")

    except FileNotFoundError:
        console.error("Claude Code CLI not found.")
        console.muted("Install it from: https://claude.ai/code")
        raise SystemExit(1) from None


def _check_auth_status() -> None:
    """Check if Claude Code is authenticated."""
    console.print()
    console.header("Authentication Status")
    console.print()

    try:
        # Try a simple prompt to check auth
        # Using a minimal prompt that should return quickly
        result = subprocess.run(
            ["claude", "--print", "-p", "respond with just: ok"],
            capture_output=True,
            text=True,
            timeout=30,
        )

        if result.returncode == 0 and "ok" in result.stdout.lower():
            console.success("Authenticated with Claude Code")
            console.hint("Ready to run: laida run 0 0")
        else:
            stderr = result.stderr.lower()
            if any(p in stderr for p in ["not logged", "not authenticated", "unauthorized"]):
                console.error("Not authenticated with Claude Code")
                console.hint("Run 'laida login' to authenticate.")
                raise SystemExit(1)
            else:
                console.warning("Could not verify authentication status")
                console.muted(f"Response: {result.stderr[:200] if result.stderr else 'none'}")

    except subprocess.TimeoutExpired:
        console.warning("Authentication check timed out")
        console.hint("Try running 'laida login' to re-authenticate.")

    except FileNotFoundError:
        console.error("Claude Code CLI not found.")
        console.muted("Install it from: https://claude.ai/code")
        raise SystemExit(1) from None
