#!/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
    echo "Running markdownlint..."
    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
            # Extract text, strip markdown syntax, check spelling
            ERRORS=$(cat "$file" | aspell list --mode=markdown --personal=./.aspell.personal 2>/dev/null | sort -u)
            if [ ! -z "$ERRORS" ]; then
                echo "⚠️  Possible misspellings in $file:"
                echo "$ERRORS" | sed 's/^/    /'
                MISSPELLED=1
            fi
        done
        if [ $MISSPELLED -eq 1 ]; then
            echo ""
            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
