#!/bin/bash
#
# Contextual post-commit hook
# Triggers incremental indexing after each commit
#
# This hook runs as a fully detached background process to never block git.
# It acquires a lock file to prevent concurrent indexing operations.

# Close all file descriptors to fully detach from git
exec 0<&-         # Close stdin
exec 1>/dev/null  # Close stdout
exec 2>/dev/null  # Close stderr

# Check if contextual is available
if ! command -v contextual &> /dev/null; then
    exit 0
fi

# Lock file to prevent concurrent indexing
LOCK_FILE=".git/contextual-index.lock"

# Try to acquire lock (non-blocking)
if ! mkdir "$LOCK_FILE" 2>/dev/null; then
    # Another indexing process is running, skip
    exit 0
fi

# Ensure lock is released on exit (even if script crashes)
trap 'rm -rf "$LOCK_FILE"' EXIT

# Run incremental indexing in background
# --incremental: only index changed files since last indexed commit
# --quiet: suppress output (we're detached anyway)
nohup contextual index --incremental --quiet &

# Disown the background process so it survives shell exit
disown

# Always exit 0 so git never fails
exit 0
