#!/bin/bash

# Configuration
CONFIG_FILE="$(dirname "$0")/.clang-format"
TARGET_DIRS=("Source" "Private" "Public" "Classes")
FILE_EXTS=("*.h" "*.cpp" "*.hpp" "*.c")
DRY_RUN=false
VERBOSE=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run) DRY_RUN=true; shift ;;
        --verbose) VERBOSE=true; shift ;;
        --config) CONFIG_FILE="$2"; shift 2 ;;
        *) echo "Unknown option: $1"; exit 1 ;;
    esac
done

# Find all source files
FILES=()

for dir in "../${TARGET_DIRS[@]}"; do
    for ext in "${FILE_EXTS[@]}"; do
        while IFS= read -r -d $'\0' file; do
            FILES+=("$file")
        done < <(find "$(pwd)/$dir" -name "$ext" -print0)
    done
done

# Formatting command
FORMAT_CMD="./clang-format -style=file:$CONFIG_FILE -i"
$DRY_RUN && FORMAT_CMD+=" --dry-run --Werror"

# Execute formatting
ERRORS=0
for file in "${FILES[@]}"; do
    if $VERBOSE; then
        echo "Checking $file"
    fi
    if ! $FORMAT_CMD "$file"; then
        ((ERRORS++))
    fi
done

if [ $ERRORS -gt 0 ]; then
    echo "❌ $ERRORS files need formatting!"
    exit 1
else
    echo "✅ All files formatted correctly!"
    exit 0
fi