# .husky/pre-commit

# Load .env variables from the project root, line by line
if [ -f .env ]; then
    while IFS='=' read -r key value || [ -n "$key" ]; do
        # Skip lines that are comments or do not contain valid key=value format
        if echo "$key" | grep -Eq '^[A-Za-z_][A-Za-z0-9_]*$'; then
            export "$key=$value"
        fi
    done < .env
fi

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

# Separate PHP files from other files, only if there are staged files
if [ -n "$STAGED_FILES" ]; then
    PHP_FILES=$(echo "$STAGED_FILES" | grep '\.php$' || true)
    OTHER_FILES=$(echo "$STAGED_FILES" | grep -v '\.php$' || true)
else
    PHP_FILES=""
    OTHER_FILES=""
fi

# Exit early if there are no files staged (unlikely, but for safety)
if [ -z "$STAGED_FILES" ]; then
    echo "No files staged for commit. Exiting."
    exit 0
fi

# Run Pint for PHP files only
if [ -n "$PHP_FILES" ]; then
    if [ "$USE_DOCKER" = "true" ]; then
        echo "Running Pint in Docker for PHP files..."
        docker compose exec -T php vendor/bin/pint $PHP_FILES
        if [ $? -ne 0 ]; then
            echo "Pint failed while running inside Docker."
            exit 1
        fi
    else
        echo "Running Pint locally for PHP files..."
        vendor/bin/pint $PHP_FILES
        if [ $? -ne 0 ]; then
            echo "Pint failed while running locally."
            exit 1
        fi
    fi

    # Restage PHP files after Pint formatting
    echo "$PHP_FILES" | xargs -r git add
fi

# Restage all non-PHP files
if [ -n "$OTHER_FILES" ]; then
    echo "$OTHER_FILES" | xargs -r git add
fi

echo "Pre-commit hook completed successfully."

exit 0
