#!/usr/bin/env python3
"""Pre-commit hook to enforce import-time budgets with actionable output."""

import os
import subprocess
import sys
from pathlib import Path


# Maximum allowed import time in seconds
MAX_IMPORT_TIME = 0.4

# Modules to check
MODULES = ["speedy_utils", "llm_utils", "vision_utils"]

def _find_repo_root() -> Path:
    """
    Find the repo root so the hook works regardless of where it's installed.

    - When installed in `.git/hooks/`, `__file__` is under `.git/`.
    - When run from `.githooks/`, `__file__` is under `.githooks/`.
    """
    start = Path(__file__).resolve()
    for parent in (start, *start.parents):
        if (parent / "pyproject.toml").is_file() and (parent / "src").is_dir():
            return parent
    # Fallback: ask git (best-effort).
    try:
        out = subprocess.check_output(
            ["git", "rev-parse", "--show-toplevel"],
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()
        if out:
            return Path(out)
    except Exception:
        pass
    return Path.cwd()


def _pick_python_executable(repo_root: Path) -> str:
    """
    Prefer the project's virtualenv if present.

    This prevents "import error" when the hook is executed by a system Python.
    """
    venv_python = repo_root / ".venv" / "bin" / "python"
    if venv_python.is_file():
        return str(venv_python)
    return sys.executable


_REPO_ROOT = _find_repo_root()
_SRC_DIR = _REPO_ROOT / "src"
_PYTHON = _pick_python_executable(_REPO_ROOT)


def _build_env() -> dict[str, str]:
    env = os.environ.copy()
    if _SRC_DIR.is_dir():
        existing = env.get("PYTHONPATH", "")
        env["PYTHONPATH"] = (
            f"{_SRC_DIR}{os.pathsep}{existing}" if existing else str(_SRC_DIR)
        )
    return env


def _helper_script() -> Path:
    return _REPO_ROOT / "scripts" / "debug_import_time.py"


def main() -> int:
    """Run import-time checks through the shared helper script."""
    print("Checking import times... (max: {:.1f}s)".format(MAX_IMPORT_TIME))

    helper = _helper_script()
    result = subprocess.run(
        [
            _PYTHON,
            str(helper),
            "--max-total-sec",
            str(MAX_IMPORT_TIME),
            "--min-sec",
            "0.01",
            "--top",
            "12",
            "--no-stdlib",
            "--quiet-success",
            *MODULES,
        ],
        env=_build_env(),
        cwd=str(_REPO_ROOT),
    )

    if result.returncode != 0:
        print("\nImport time check failed.")
        print("Rerun the helper above after moving heavy imports into function scope")
        print("or a lazy __getattr__ export to pinpoint the slow path.")

    return result.returncode


if __name__ == "__main__":
    sys.exit(main())
