#!/bin/sh
# Collab git hook (installed by `collab init-hooks`).
# Acquires locks for staged files, then runs the pre-commit framework.
#
# Resolves the project virtualenv first so IDE git (VS Code/Cursor Source
# Control) and chained `language: system` hooks use the same tools as an
# activated terminal, even when no venv is on PATH.

PROJECT_ROOT="$(git rev-parse --show-toplevel)"
LOCK_STRICT="${LOCK_STRICT:-0}"

VENV_SCRIPTS="$PROJECT_ROOT/.venv/Scripts"
VENV_BIN="$PROJECT_ROOT/.venv/bin"
if [ -d "$VENV_SCRIPTS" ]; then
    PATH="$VENV_SCRIPTS:$PATH"
    export PATH
fi
if [ -d "$VENV_BIN" ]; then
    PATH="$VENV_BIN:$PATH"
    export PATH
fi

PYTHON="$PROJECT_ROOT/.venv/Scripts/python.exe"
if [ ! -x "$PYTHON" ]; then
    PYTHON="$PROJECT_ROOT/.venv/bin/python"
fi
if [ ! -x "$PYTHON" ]; then
    PYTHON="python"
fi

run_precommit_framework() {
    PRE_COMMIT_BIN="$PROJECT_ROOT/.venv/Scripts/pre-commit.exe"
    if [ ! -x "$PRE_COMMIT_BIN" ]; then
        PRE_COMMIT_BIN="$PROJECT_ROOT/.venv/bin/pre-commit"
    fi
    if [ ! -x "$PRE_COMMIT_BIN" ]; then
        PRE_COMMIT_BIN="$(command -v pre-commit 2>/dev/null || true)"
    fi
    if [ -n "$PRE_COMMIT_BIN" ] && [ -x "$PRE_COMMIT_BIN" ]; then
        exec "$PRE_COMMIT_BIN" run --hook-stage pre-commit "$@"
    fi
    exit 0
}

STAGED="$(git diff --cached --name-only --diff-filter=ACMR)"
if [ -z "$STAGED" ]; then
    run_precommit_framework "$@"
fi

# Verify the canonical runtime is importable. An unrelated PyPI package named
# 'collab' will not expose collab.githooks, so this reliably distinguishes the
# correct 'collab-runtime' distribution from a name-collision install.
if ! "$PYTHON" -c "import collab.githooks" >/dev/null 2>&1; then
    echo "[collab] Warning: collab-runtime not importable; lock acquisition skipped." >&2
    echo "[collab]   Install the canonical runtime (never 'pip install collab'):" >&2
    echo "[collab]   pip install collab-runtime" >&2
    if [ "$LOCK_STRICT" = "1" ]; then
        echo "[collab] LOCK_STRICT=1 -> blocking commit." >&2
        exit 1
    fi
    run_precommit_framework "$@"
fi

"$PYTHON" -m collab.githooks acquire-staged
LOCK_EXIT=$?
if [ $LOCK_EXIT -ne 0 ]; then
    echo "" >&2
    echo "[collab] Commit aborted due to file lock conflicts." >&2
    echo "[collab] To view details: collab active" >&2
    echo "[collab] To open dashboard: collab dashboard" >&2
    exit 1
fi

echo "[collab] Locks OK - running project validations..." >&2
run_precommit_framework "$@"
