#!/usr/bin/env bash
# tools/worktree-precommit-gate.sh — ручной прогон pre-commit гейта в worktree.
#
# Закрывает квирки #86/#97: в worktree git-хук .git/hooks/pre-commit (shared
# через worktree's gitdir pointer) не находит бинарь lefthook в PATH worktree
# и тихо пропускает все гейты (pint + larastan + pest + gitleaks protect
# --staged). Этот скрипт хардкодит абсолютный путь к lefthook.exe и явно гонит
# конфиг lefthook.yml из main checkout.
#
# Использование (из любого worktree):
#   bash "/c/моя/проекты/портал crm/Документация/tools/worktree-precommit-gate.sh"
#
# Exit code: 0 если все гейты прошли, иначе ненулевой (lefthook propagate'ит).
# Запускать ДО `git commit` — git commit не вызовет lefthook автоматически в
# worktree, поэтому это явный шаг.

set -euo pipefail

MAIN_REPO="/c/моя/проекты/портал crm/Документация"
LEFTHOOK_BIN="${MAIN_REPO}/node_modules/lefthook-windows-x64/bin/lefthook.exe"
LEFTHOOK_CONFIG="${MAIN_REPO}/lefthook.yml"

if [[ ! -x "${LEFTHOOK_BIN}" ]]; then
  echo "ERROR: lefthook.exe not found at: ${LEFTHOOK_BIN}" >&2
  echo "Run \`npm install\` in main repo to restore." >&2
  exit 2
fi

if [[ ! -f "${LEFTHOOK_CONFIG}" ]]; then
  echo "ERROR: lefthook.yml not found at: ${LEFTHOOK_CONFIG}" >&2
  exit 2
fi

# Auto-detect: are we in worktree or main repo?
CURRENT_TOPLEVEL="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -z "${CURRENT_TOPLEVEL}" ]]; then
  echo "ERROR: not inside a git work tree" >&2
  exit 2
fi

# Normalize MAIN_REPO via git so trailing slashes / casing don't matter.
MAIN_REPO_NORM="$(cd "${MAIN_REPO}" && git rev-parse --show-toplevel)"

if [[ "${CURRENT_TOPLEVEL}" == "${MAIN_REPO_NORM}" ]]; then
  CONTEXT="main checkout"
else
  CONTEXT="worktree (${CURRENT_TOPLEVEL})"
fi

echo "[worktree-gate] context: ${CONTEXT}"
echo "[worktree-gate] lefthook: ${LEFTHOOK_BIN}"
echo "[worktree-gate] config:   ${LEFTHOOK_CONFIG}"
echo "[worktree-gate] running pre-commit..."
echo

# Lefthook reads its config relative to cwd OR via -c. Use -c для надёжности
# в worktree (там lefthook.yml — это файл из main repo, не локальный).
exec "${LEFTHOOK_BIN}" -c "${LEFTHOOK_CONFIG}" run pre-commit
