#!/bin/sh

# DanceLessonsCoach pre-commit hook
# Runs go mod tidy, go fmt, and suggests issue references before allowing commits

echo "Running pre-commit hooks..."

# Suggest issue references first (before any changes)
if [ -f ".vibe/skills/commit_message/scripts/suggest-issue-reference.sh" ]; then
    echo "Checking for relevant issues..."
    ./.vibe/skills/commit_message/scripts/suggest-issue-reference.sh || true
    echo ""
fi

# Check if we're in a Go project
if [ ! -f "go.mod" ]; then
    echo "Not a Go project, skipping Go-specific hooks"
    exit 0
fi

# Run go mod tidy
echo "Running go mod tidy..."
go mod tidy
if [ $? -ne 0 ]; then
    echo "ERROR: go mod tidy failed"
    exit 1
fi

# Check if go.mod or go.sum were modified
if git diff --cached --name-only | grep -qE '(go\.mod|go\.sum)'; then
    echo "go.mod or go.sum changed, adding to commit..."
    git add go.mod go.sum
fi

# Run go fmt on staged Go files only
echo "Running go fmt on staged files..."
STAGED_GOFILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
if [ -n "$STAGED_GOFILES" ]; then
    gofmt -w $STAGED_GOFILES
    if [ $? -ne 0 ]; then
        echo "ERROR: go fmt failed"
        exit 1
    fi
    
    # Add formatted files to commit
    git add $STAGED_GOFILES
fi

echo "Pre-commit hooks completed successfully"
exit 0