#!/usr/bin/env sh
# Git post-commit hook: index changed files into RAG vector DB for the current story.
# Install: cp scripts/post-commit .git/hooks/post-commit && chmod +x .git/hooks/post-commit
# Requires: RAG_REPO_PATH, RAG_DB_DSN, RAG_EMBEDDINGS_DIM; story from RAG_STORY or .rag-story or current branch name.

set -e
cd "$(git rev-parse --show-toplevel)"

# Resolve story: env RAG_STORY > file .rag-story > current branch name
if [ -n "${RAG_STORY}" ]; then
  STORY="${RAG_STORY}"
elif [ -f .rag-story ]; then
  STORY=$(head -n1 .rag-story | tr -d '\n\r')
else
  STORY=$(git branch --show-current)
fi

if [ -z "$STORY" ]; then
  echo "post-commit: RAG_STORY or .rag-story or branch name required for indexing."
  exit 0
fi

# Run index: all changes in the story (main..HEAD), not per-commit
if command -v rag-agent >/dev/null 2>&1; then
  rag-agent index --changed --base-ref main --head-ref HEAD --story "$STORY"
elif [ -n "${VIRTUAL_ENV}" ]; then
  rag-agent index --changed --base-ref main --head-ref HEAD --story "$STORY"
else
  if [ -f "venv/bin/rag-agent" ]; then
    venv/bin/rag-agent index --changed --base-ref main --head-ref HEAD --story "$STORY"
  else
    PYTHONPATH=src python -m rag_agent.cli index --changed --base-ref main --head-ref HEAD --story "$STORY" 2>/dev/null || true
  fi
fi
