#!/bin/bash
# Nexus-Dev Pre-commit Hook

set -e

# Find project root by walking up to find nexus_config.json
REPO_ROOT=$(git rev-parse --show-toplevel)
PROJECT_ROOT="$REPO_ROOT"

# Walk up from repo root to find nexus_config.json
CURRENT="$REPO_ROOT"
while [ "$CURRENT" != "/" ]; do
    if [ -f "$CURRENT/nexus_config.json" ]; then
        PROJECT_ROOT="$CURRENT"
        break
    fi
    CURRENT=$(dirname "$CURRENT")
done

# Verify we found a config
if [ ! -f "$PROJECT_ROOT/nexus_config.json" ]; then
    echo "⚠️  Nexus-Dev: No nexus_config.json found. Skipping indexing."
    exit 0
fi

# Change to project root for indexing
cd "$PROJECT_ROOT" || exit 0

echo "🧠 Nexus-Dev: Checking for files to index..."
echo "📍 Project root: $PROJECT_ROOT"

# Get list of modified/added code files
MODIFIED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(py|js|jsx|ts|tsx|java)$' || true)

if [ -n "$MODIFIED_FILES" ]; then
    echo "📁 Indexing modified code files..."
    for file in $MODIFIED_FILES; do
        if [ -f "$file" ]; then
            python -m nexus_dev.cli index "$file" --quiet 2>/dev/null || true
        fi
    done
fi

# Index any new lesson files
LESSON_FILES=$(git diff --cached --name-only --diff-filter=A | grep -E '^\.nexus/lessons/.*\.md$' || true)

if [ -n "$LESSON_FILES" ]; then
    echo "📚 Indexing new lessons..."
    for file in $LESSON_FILES; do
        if [ -f "$file" ]; then
            python -m nexus_dev.cli index-lesson "$file" --quiet 2>/dev/null || true
        fi
    done
fi

echo "✅ Nexus-Dev indexing complete"
