#!/bin/sh
# Native git pre-commit hook for media-archive-sync
# Runs linting and quick tests before allowing commits

set -e

echo "Running pre-commit checks..."

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if we're in a virtual environment
if [ -z "$VIRTUAL_ENV" ] && [ -z "$CONDA_DEFAULT_ENV" ]; then
    echo "${YELLOW}Warning: Not in a virtual environment${NC}"
fi

# Get list of staged Python files (null-terminated)
# Save to temp file to avoid shell variable issues with null bytes
STAGED_PY_FILE=$(mktemp)
git diff --cached --name-only -z --diff-filter=ACM | grep -z '\.py$' > "$STAGED_PY_FILE" || true

# Check if we have any Python files staged
if [ ! -s "$STAGED_PY_FILE" ]; then
    rm -f "$STAGED_PY_FILE"
    echo "${GREEN}No Python files staged for commit.${NC}"
    exit 0
fi

# Count files for display
echo "Staged Python files:"
cat "$STAGED_PY_FILE" | tr '\0' '\n'
echo ""

# Run Ruff linter
echo "Running Ruff linter..."
if command -v ruff >/dev/null 2>&1; then
    cat "$STAGED_PY_FILE" | xargs -0 ruff check --fix
    # Re-stage any files that were auto-fixed
    cat "$STAGED_PY_FILE" | xargs -0 git add
    echo "${GREEN}Ruff checks passed${NC}"
else
    echo "${YELLOW}ruff not found, skipping...${NC}"
fi

# Run Black formatter check
echo "Running Black formatter..."
if command -v black >/dev/null 2>&1; then
    cat "$STAGED_PY_FILE" | xargs -0 black --check --diff 2>/dev/null || {
        echo "${YELLOW}Running black to fix formatting...${NC}"
        cat "$STAGED_PY_FILE" | xargs -0 black
        cat "$STAGED_PY_FILE" | xargs -0 git add
        echo "${GREEN}Formatting fixed and staged${NC}"
    }
    echo "${GREEN}Black checks passed${NC}"
else
    echo "${YELLOW}black not found, skipping...${NC}"
fi

# Cleanup temp file
rm -f "$STAGED_PY_FILE"

# Run quick tests
echo "Running quick tests..."
if command -v pytest >/dev/null 2>&1; then
    pytest -x -q --tb=short --disable-warnings 2>/dev/null || {
        echo "${RED}Tests failed!${NC}"
        exit 1
    }
    echo "${GREEN}Tests passed${NC}"
else
    echo "${YELLOW}pytest not found, skipping tests...${NC}"
fi

echo "${GREEN}All pre-commit checks passed!${NC}"
exit 0
