#!/bin/bash
# Template Version: 2 | ContextKit: 0.1.0 | Updated: 2025-09-16

# auto-format.sh - Auto-format edited files
# Called by PostToolUse hook after Claude Code edits files

# ⚠️ FOR DEVELOPERS: Do not edit this file - changes will be overwritten during ContextKit updates.
# Report bugs: https://github.com/FlineDev/ContextKit/issues

## Purpose
# When file edits occur, detect if it's a Swift file and run SwiftFormat + swift-format
# only on that specific file (not entire project) to ensure immediate code consistency
# without performance impact.

set -e

# Define function BEFORE it's called
format_swift_file() {
    local file="$1"

    echo "📝 Auto-formatting Swift file: $file"

    # Apply SwiftFormat first (adds explicit self, structure)
    if command -v swiftformat &> /dev/null; then
        if [ -f ".swiftformat" ]; then
            swiftformat "$file" --config .swiftformat --quiet
        else
            swiftformat "$file" --quiet
        fi
        echo "  ✅ SwiftFormat applied"
    else
        echo "  ⚠️  SwiftFormat not found - install with: brew install swiftformat"
    fi

    # Apply swift-format second (line breaks, Apple style)
    if command -v swift-format &> /dev/null; then
        if [ -f ".swift-format" ]; then
            swift-format --in-place "$file" --configuration .swift-format
        else
            swift-format --in-place "$file"
        fi
        echo "  ✅ swift-format applied"
    else
        echo "  ⚠️  swift-format not found - install Xcode Command Line Tools with: xcode-select --install"
    fi
}

# Extract file path from Claude Code hook JSON input
FILE_PATH=$(jq -r '.tool_input.file_path' 2>/dev/null)

# Exit early if no file path or jq failed
if [ -z "$FILE_PATH" ] || [ "$FILE_PATH" = "null" ]; then
    exit 0
fi

# Skip if file doesn't exist (might have been deleted)
if [ ! -f "$FILE_PATH" ]; then
    exit 0
fi

# Only format Swift files
case "$FILE_PATH" in
    *.swift)
        format_swift_file "$FILE_PATH"
        ;;
    *)
        # Skip non-Swift files silently
        exit 0
        ;;
esac