#!/bin/bash
#
# Pre-commit hook to automatically format C++ files with clang-format
# This hook formats staged .cpp and .h files before commit
#

# Redirect output to stderr
exec 1>&2

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

# Check if clang-format is available
if ! command -v clang-format &> /dev/null; then
    echo -e "${YELLOW}Warning: clang-format not found. Skipping formatting.${NC}"
    exit 0
fi

# Get the root directory of the repository
REPO_ROOT=$(git rev-parse --show-toplevel)
cd "$REPO_ROOT" || exit 1

# Find staged C++ files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(cpp|h|hpp|c|cc)$')

if [ -z "$STAGED_FILES" ]; then
    # No C++ files staged, nothing to do
    exit 0
fi

echo -e "${GREEN}Running clang-format on staged C++ files...${NC}"

# Track if any files were modified
MODIFIED=0

# Format each staged file
for FILE in $STAGED_FILES; do
    if [ -f "$FILE" ]; then
        # Check if file needs formatting
        if clang-format --dry-run --Werror "$FILE" &> /dev/null; then
            # File is already formatted
            continue
        else
            # File needs formatting
            echo -e "  Formatting: ${FILE}"
            clang-format -i "$FILE"
            git add "$FILE"
            MODIFIED=1
        fi
    fi
done

if [ $MODIFIED -eq 1 ]; then
    echo -e "${GREEN}✓ Files have been automatically formatted.${NC}"
    echo -e "${YELLOW}Note: The formatted files have been re-staged.${NC}"
fi

exit 0



