#!/bin/bash

# Pre-commit hook: Run unit and integration tests
# All tests in tests/unit/ and tests/integration/ must pass before commit

set -e

echo "🧪 Running pre-commit tests..."
echo ""

# Set PYTHONPATH
export PYTHONPATH="src:$PYTHONPATH"

# CRITICAL: Prevent tests from polluting the real Git repository
# Get Python's temp directory and set GIT_CEILING_DIRECTORIES to its parent
# This prevents Git from searching upward and finding the project's .git
PYTHON_TMPDIR=$(python3 -c "import tempfile, os; print(os.path.dirname(tempfile.gettempdir()))")
export GIT_CEILING_DIRECTORIES="$PYTHON_TMPDIR"

# WORKTREE FIX: Clear all git environment variables that might interfere with tests
# When running in a git worktree, these variables can cause test failures
unset GIT_DIR
unset GIT_WORK_TREE
unset GIT_INDEX_FILE
unset GIT_OBJECT_DIRECTORY
unset GIT_ALTERNATE_OBJECT_DIRECTORIES

echo "🔒 Git isolation enabled: GIT_CEILING_DIRECTORIES=$GIT_CEILING_DIRECTORIES"

# Run unit and integration tests
echo "Running tests/unit and tests/integration..."
python3 -m pytest tests/unit/ tests/integration/ -v --tb=short -q

# Check exit code
if [ $? -eq 0 ]; then
    echo ""
    echo "✅ All tests passed! Proceeding with commit..."
    exit 0
else
    echo ""
    echo "❌ Tests failed! Please fix the failing tests before committing."
    exit 1
fi
