#!/usr/bin/env bash

set -e

echo "Running pre-commit checks..."

# Get list of staged markdown files
STAGED_MD_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.md$' || true)

if [ -z "$STAGED_MD_FILES" ]; then
    echo "No markdown files to check."
    exit 0
fi

echo "Checking markdown files..."

# Check markdown formatting with markdownlint-cli
if command -v markdownlint &> /dev/null; then
    markdownlint $STAGED_MD_FILES || {
        echo "❌ Markdown linting failed. Fix issues or use 'git commit --no-verify' to skip."
        exit 1
    }
else
    echo "⚠️  markdownlint not found, skipping markdown linting"
fi

# Spell check
if command -v aspell &> /dev/null; then
    # Check if aspell can find dictionaries
    if ! aspell dump dicts 2>/dev/null | grep -q "en"; then
        echo "⚠️  aspell found but no English dictionaries available"
        echo "    Make sure ASPELL_CONF is set correctly in your direnv"
        echo "    Skipping spell check"
    else
        echo "Running spell check..."
        MISSPELLED=0
        for file in $STAGED_MD_FILES; do
            # Get list of misspelled words
            ERRORS=$(cat "$file" | aspell list --mode=markdown --lang=en --personal=./.aspell.en.pws 2>/dev/null | sort -u)
            if [ ! -z "$ERRORS" ]; then
                echo "⚠️  Possible misspellings in $file:"
                # For each misspelled word, show context
                while IFS= read -r word; do
                    if [ ! -z "$word" ]; then
                        SUGGESTION=$(echo "$word" | aspell pipe --mode=markdown --lang=en --personal=./.aspell.en.pws 2>/dev/null | grep -E "^&" | cut -d: -f2 | cut -d, -f1 | sed 's/^ //')
                        echo " '$word'   →   suggestion: $SUGGESTION"
                        # Use grep to find lines containing the word (case-insensitive) with line numbers
                        grep -n -i -w --color=always "$word" "$file" | head -3 | while IFS= read -r line; do
                            echo "      $line"
                        done
                    fi
                done <<< "$ERRORS"
                MISSPELLED=1
                echo ""
            fi
        done
        if [ $MISSPELLED -eq 1 ]; then
            echo "Review spelling errors above. Add correct terms to .aspell.personal"
            echo "Use 'git commit --no-verify' to skip if needed."
            exit 1
        fi
    fi
else
    echo "⚠️  aspell not found, skipping spell check"
fi

echo "✅ Pre-commit checks passed!"
exit 0
