#!/bin/bash

# Pre-commit hook to run pytest and pylint on staged files
# Exit on any error
set -e

echo "Running pre-commit checks..."

# Get list of staged files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)

# Check if there are any staged files
if [ -z "$STAGED_FILES" ]; then
    echo "No files staged for commit."
    exit 0
fi

# Initialize error tracking
ERRORS=0

# Function to run pytest on test files
run_pytest() {
    local test_files=()
    
    # Find staged test files
    for file in $STAGED_FILES; do
        if [[ $file == *_test.py ]] || [[ $file == test_*.py ]] || [[ $file == tests/* ]]; then
            if [ -f "$file" ]; then
                test_files+=("$file")
            fi
        fi
    done
    
    # Run pytest if there are test files
    if [ ${#test_files[@]} -gt 0 ]; then
        echo "Running pytest on staged test files:"
        printf '%s\n' "${test_files[@]}"
        
        if ! python -m pytest "${test_files[@]}" -v; then
            echo "❌ pytest failed on staged test files"
            ERRORS=$((ERRORS + 1))
        else
            echo "✅ pytest passed on staged test files"
        fi
    else
        echo "No staged test files found"
    fi
}

# Function to run pylint on Python files
run_pylint() {
    local python_files=()
    
    # Find staged Python files
    for file in $STAGED_FILES; do
        if [[ $file == *.py ]]; then
            if [ -f "$file" ]; then
                python_files+=("$file")
            fi
        fi
    done
    
    # Run pylint if there are Python files
    if [ ${#python_files[@]} -gt 0 ]; then
        echo "Running pylint on staged Python files:"
        printf '%s\n' "${python_files[@]}"
        
        if ! python -m pylint "${python_files[@]}" --rcfile=.pylintrc; then
            echo "❌ pylint failed on staged Python files"
            ERRORS=$((ERRORS + 1))
        else
            echo "✅ pylint passed on staged Python files"
        fi
    else
        echo "No staged Python files found"
    fi
}

# Run the checks
run_pytest
run_pylint

# Exit with error if any checks failed
if [ $ERRORS -gt 0 ]; then
    echo ""
    echo "❌ Pre-commit checks failed. Please fix the issues above before committing."
    echo "You can bypass this hook with: git commit --no-verify"
    exit 1
else
    echo ""
    echo "✅ All pre-commit checks passed!"
    exit 0
fi 