#!/bin/bash
# Post-commit hook for incremental codebase indexing
# Automatically updates RuVector index with committed files
#
# Install: ln -s ../../.claude/hooks/post-commit-codebase-index .git/hooks/post-commit

set -euo pipefail

SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../skills/ruvector-codebase-index" && pwd)"
INDEX_SCRIPT="$SKILL_DIR/index.sh"
MOVE_HANDLER="$SKILL_DIR/handle-file-moves.sh"

# Colors
BLUE='\033[0;34m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${BLUE}[RuVector]${NC} Post-commit indexing hook triggered"

# Check if indexing is enabled
if [[ "${RUVECTOR_AUTO_INDEX:-true}" != "true" ]]; then
  echo -e "${YELLOW}[RuVector]${NC} Auto-indexing disabled (set RUVECTOR_AUTO_INDEX=true to enable)"
  exit 0
fi

# Check if API key is available
if [[ -z "${OPENAI_API_KEY:-}" && -z "${ZAI_API_KEY:-}" ]]; then
  echo -e "${YELLOW}[RuVector]${NC} Skipping indexing: No API key found"
  exit 0
fi

# STEP 1: Handle file moves/renames (delete old entries, index new locations)
echo -e "${BLUE}[RuVector]${NC} Checking for file moves..."
"$MOVE_HANDLER" --from-commit 2>&1 | tee -a /tmp/ruvector-moves.log

# STEP 2: Get list of added/modified files from the last commit
COMMITTED_FILES=$(git diff-tree --no-commit-id --name-only --diff-filter=AM -r HEAD 2>/dev/null || echo "")

if [[ -z "$COMMITTED_FILES" ]]; then
  echo -e "${YELLOW}[RuVector]${NC} No files to index"
  exit 0
fi

# Filter for indexable files
CONFIG_FILE="$SKILL_DIR/config.json"
INDEXABLE_EXTENSIONS=$(jq -r '.indexableExtensions[]' "$CONFIG_FILE" 2>/dev/null || echo "")

INDEXABLE_FILES=()
while IFS= read -r file; do
  if [[ -f "$file" ]]; then
    ext=".${file##*.}"
    if echo "$INDEXABLE_EXTENSIONS" | grep -q "$ext"; then
      INDEXABLE_FILES+=("$file")
    fi
  fi
done <<< "$COMMITTED_FILES"

if [[ ${#INDEXABLE_FILES[@]} -eq 0 ]]; then
  echo -e "${YELLOW}[RuVector]${NC} No indexable files in commit"
  exit 0
fi

echo -e "${BLUE}[RuVector]${NC} Indexing ${#INDEXABLE_FILES[@]} file(s)..."

# Run indexing in background to not block git operations
(
  "$INDEX_SCRIPT" --files "${INDEXABLE_FILES[@]}" > /tmp/ruvector-index.log 2>&1
  echo -e "${GREEN}[RuVector]${NC} Index updated successfully"
) &

# Don't wait for indexing to complete
echo -e "${BLUE}[RuVector]${NC} Indexing started in background (check /tmp/ruvector-index.log for details)"

exit 0
