"""Claude Code authentication — CLI detection + auth check.

Auth strategy: Claude CLI handles its own auth inside Docker containers.
We just pass CLAUDE_CODE_OAUTH_TOKEN env var for CI/test scenarios.
"""

from __future__ import annotations

import os
import shutil
import subprocess
from pathlib import Path

from ievo.core.global_config import set_config
from ievo.utils.console import info, step, success, warn


def check_claude_cli() -> bool:
    """Check if Claude Code CLI is installed."""
    return shutil.which("claude") is not None


def check_claude_auth() -> str | None:
    """Check if Claude CLI is authenticated. Returns account info or None."""
    if not check_claude_cli():
        return None
    try:
        result = subprocess.run(
            ["claude", "auth", "status"],
            capture_output=True,
            text=True,
            check=False,
            timeout=10,
        )
        if result.returncode == 0:
            output = result.stdout.strip() or result.stderr.strip()
            return output or "authenticated"
    except (FileNotFoundError, subprocess.TimeoutExpired):
        pass
    return None


def check_env_token() -> str | None:
    """Check if CLAUDE_CODE_OAUTH_TOKEN is set in environment."""
    return os.environ.get("CLAUDE_CODE_OAUTH_TOKEN")


def prompt_claude_auth(home: Path) -> str | None:
    """Interactive Claude auth flow. Returns auth method or None.

    Returns:
        "env" — using CLAUDE_CODE_OAUTH_TOKEN from environment
        "cli" — authenticated via claude CLI
        None — skipped
    """
    info("[bold]Claude Code authentication[/bold]")

    # 1. Check environment variable
    env_token = check_env_token()
    if env_token:
        success("CLAUDE_CODE_OAUTH_TOKEN found in environment")
        set_config(home, "claude_auth", "env")
        return "env"

    # 2. Check if Claude CLI is available and authenticated
    if check_claude_cli():
        auth_info = check_claude_auth()
        if auth_info:
            success("Claude Code CLI authenticated")
            set_config(home, "claude_auth", "cli")
            return "cli"

        # Claude CLI installed but not authenticated
        step("Claude Code CLI found but not authenticated")
        answer = input("  Run 'claude auth login' now? (Y/n): ").strip().lower()
        if answer in ("", "y", "yes"):
            try:
                subprocess.run(
                    ["claude", "auth", "login"],
                    check=False,
                    timeout=120,
                )
                auth_info = check_claude_auth()
                if auth_info:
                    success("Claude Code CLI authenticated")
                    set_config(home, "claude_auth", "cli")
                    return "cli"
            except (FileNotFoundError, subprocess.TimeoutExpired):
                pass
            warn("Claude auth login did not complete")

    else:
        step("Claude Code CLI not found")
        info("Install: [bold]npm install -g @anthropic-ai/claude-code[/bold]")

    # 3. No auth available
    warn("Claude auth not configured. Agent runs will fail without it.")
    info("Set CLAUDE_CODE_OAUTH_TOKEN or run [bold]claude auth login[/bold].")
    return None
