#!/usr/bin/env bash

GREEN='\033[0;32m'
NC='\033[0m' # No Color

echo "Running pre-commit checks..."

# Track overall success/failure
OVERALL_RESULT=0

# 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
    if ! markdownlint $STAGED_MD_FILES; then
        echo "❌ Markdown linting failed."
        OVERALL_RESULT=1
    else
        echo -e "${GREEN}✅ Markdownlint passed!${NC}"
    fi
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"
                echo -e "\nMisspelled words:\n"
                while IFS= read -r word; do
                    echo "$word"
                done <<< "$ERRORS"
                MISSPELLED=1
                echo ""
            fi
        done
        if [ $MISSPELLED -eq 1 ]; then
            echo "❌ Spell check failed."
            OVERALL_RESULT=1
        fi
    fi
else
    echo "⚠️  aspell not found, skipping spell check"
fi

# Link validation
if [ -x "./scripts/check-links.sh" ]; then
    echo "Running link validation..."
    if ! ./scripts/check-links.sh $STAGED_MD_FILES; then
        echo "❌ Link validation failed."
        OVERALL_RESULT=1
    fi
else
    echo "⚠️  Link checker script not found or not executable, skipping link validation"
fi

# Final result
if [ $OVERALL_RESULT -eq 0 ]; then
    echo "✅ Pre-commit checks passed!"
    exit 0
else
    echo ""
    echo "❌ Some pre-commit checks failed. Fix issues or use 'git commit --no-verify' to skip."
    exit 1
fi
