#!/usr/bin/env bash

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

echo "Running pre-commit checks..."

# Auto-update lastmod in content files (non-blocking)
# Runs before other checks so lint/spell run on updated files
# Resolve symlink to find the actual script directory
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
if [ -x "$SCRIPT_DIR/update-lastmod.sh" ]; then
    "$SCRIPT_DIR/update-lastmod.sh" || echo "⚠️  lastmod update script encountered an issue"
fi

# 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..."

# --- Stage 1: Markdown linting ---
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

# --- Stage 2: Interactive spell check ---
# Runs before tag check so typos in tags get corrected first
if [ -x "./scripts/spellcheck-interactive.sh" ]; then
    if ! ./scripts/spellcheck-interactive.sh $STAGED_MD_FILES; then
        echo "❌ Spell check failed."
        OVERALL_RESULT=1
    fi
else
    echo "⚠️  Spell check script not found or not executable, skipping spell check"
fi

# --- Stage 3: Tag similarity check ---
# Runs after spell check so corrected tags are compared
if command -v python3 &> /dev/null && [ -f "./scripts/check-tags.py" ]; then
    echo "Running tag similarity check..."
    if ! python3 ./scripts/check-tags.py $STAGED_MD_FILES; then
        echo "❌ Tag similarity check failed."
        OVERALL_RESULT=1
    fi
else
    echo "⚠️  Tag checker (python3 or scripts/check-tags.py) not found, skipping tag check"
fi

# --- Stage 4: 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
