#!/usr/bin/env bash
# git post-commit hook — reindex files changed in the latest commit.
# Runs after every `git commit`. Only touches Python/C# files.

REPO_ROOT="$(git rev-parse --show-toplevel)"
REINDEX="$REPO_ROOT/.venv/bin/codemind-reindex"

[[ ! -x "$REINDEX" ]] && exit 0

# For the root commit diff-tree needs --root; otherwise compare to parent.
if git rev-parse --verify HEAD~1 >/dev/null 2>&1; then
  CHANGED="$(git diff-tree --no-commit-id -r --name-only --diff-filter=ACMR HEAD 2>/dev/null \
    | grep -E '\.(py|cs)$' || true)"
else
  CHANGED="$(git ls-tree --name-only -r HEAD \
    | grep -E '\.(py|cs)$' || true)"
fi

[[ -z "$CHANGED" ]] && exit 0

while IFS= read -r rel; do
  abs="$REPO_ROOT/$rel"
  [[ -f "$abs" ]] && "$REINDEX" --repo "$REPO_ROOT" --file "$abs" 2>/dev/null || true
done <<< "$CHANGED"
