#!/usr/bin/env sh
# Server-side hook: index changed files after push. Install in bare repo: cp scripts/post-receive /path/to/repo.git/hooks/post-receive
# Requires: RAG_REPO_PATH = path to a non-bare clone of this repo (worktree), updated by this hook to newrev.
#           RAG_DB_DSN, RAG_EMBEDDINGS_DIM; optionally GIGACHAT_CREDENTIALS.
# Story is derived from ref name (e.g. refs/heads/main -> main).

set -e

if [ -z "${RAG_REPO_PATH}" ]; then
  echo "post-receive: RAG_REPO_PATH (path to clone worktree) is required. Skipping index."
  exit 0
fi

# Read refs from stdin (refname SP oldrev SP newrev LF)
while read -r refname oldrev newrev; do
  # Skip branch deletions
  if [ "$newrev" = "0000000000000000000000000000000000000000" ]; then
    continue
  fi
  # Branch name from ref (e.g. refs/heads/main -> main)
  branch="${refname#refs/heads/}"
  [ -z "$branch" ] && continue

  # Update worktree to newrev so rag-agent can read files from disk
  if [ -d "${RAG_REPO_PATH}/.git" ]; then
    git -C "${RAG_REPO_PATH}" fetch origin 2>/dev/null || true
    git -C "${RAG_REPO_PATH}" checkout -f "${newrev}" 2>/dev/null || true
  fi

  # Index all commits in the story (main..newrev), not just this push
  export RAG_REPO_PATH
  if command -v rag-agent >/dev/null 2>&1; then
    rag-agent index --changed --base-ref main --head-ref "${newrev}" --story "${branch}"
  elif [ -f "${RAG_AGENT_VENV}/bin/rag-agent" ]; then
    "${RAG_AGENT_VENV}/bin/rag-agent" index --changed --base-ref main --head-ref "${newrev}" --story "${branch}"
  else
    if [ -n "${RAG_AGENT_SRC}" ]; then
      PYTHONPATH="${RAG_AGENT_SRC}/src" "${RAG_AGENT_PYTHON:-python3}" -m rag_agent.cli index --changed --base-ref main --head-ref "${newrev}" --story "${branch}" 2>/dev/null || true
    fi
  fi
done

exit 0
