"""Helpers for locating/installing the codex-acp adapter binary."""

from __future__ import annotations

import os
import shutil
import subprocess
from pathlib import Path
from typing import Optional, Tuple


def _env_binary_path() -> Optional[Path]:
    raw = os.environ.get("VICOA_CODEX_ACP_PATH")
    if not raw:
        return None
    path = Path(os.path.expanduser(raw))
    return path if path.exists() else None


def _which_binary_path() -> Optional[Path]:
    which = shutil.which("codex-acp")
    if not which:
        return None
    path = Path(which)
    return path if path.exists() else None


def resolve_codex_acp_binary() -> Optional[Path]:
    env_path = _env_binary_path()
    if env_path:
        return env_path
    return _which_binary_path()


def ensure_codex_acp_available(
    *,
    auto_install: bool = True,
    install_timeout_seconds: int = 300,
) -> Tuple[Optional[Path], Optional[str]]:
    """Resolve codex-acp binary path, optionally auto-installing via npm."""
    resolved = resolve_codex_acp_binary()
    if resolved:
        return resolved, None

    if auto_install:
        npm = shutil.which("npm")
        if npm:
            try:
                result = subprocess.run(
                    [npm, "install", "-g", "@zed-industries/codex-acp"],
                    capture_output=True,
                    text=True,
                    timeout=install_timeout_seconds,
                    check=False,
                )
                if result.returncode == 0:
                    resolved = resolve_codex_acp_binary()
                    if resolved:
                        return resolved, None
            except Exception:
                # Fall through to final guidance message.
                pass

    return (None, "Codex ACP adapter ('codex-acp') is not installed or not on PATH.\n")
