#!/bin/sh

# Capture the list of initially staged Kotlin files
initial_staged_files=$(git diff --name-only --cached -- '*.kt')

if [ -z "$initial_staged_files" ]; then
    echo "No Kotlin files staged for commit."
    exit 0
fi

formatted_files=$(echo "$initial_staged_files" | sed 's|^app/||' | paste -sd "," -)
echo "Formatting Kotlin files: $formatted_files"
./gradlew ktfmtPrecommit --include-only="$formatted_files"

if [ $? -ne 0 ]; then
    echo "Kotlin formatting failed. Please fix the issues."
    exit 1
fi

# Re-stage only the initially staged Kotlin files
for file in $initial_staged_files; do
    git add "$file"
done

echo "Kotlin files formatted"
