#!/bin/bash

# Setup Markdown Pre-commit Hooks
# This script installs pre-commit hooks that automatically fix markdown formatting

set -e

echo "🔧 Setting up Markdown Pre-commit Hooks..."

# Check if pre-commit is installed
if ! command -v pre-commit &> /dev/null; then
    echo "📦 Installing pre-commit..."
    pip install pre-commit
else
    echo "✅ pre-commit already installed"
fi

# Create .pre-commit-config.yaml if it doesn't exist
if [ ! -f .pre-commit-config.yaml ]; then
    echo "📝 Creating .pre-commit-config.yaml..."
    cat > .pre-commit-config.yaml << 'EOF'
repos:
  - repo: https://github.com/igorshubovych/markdownlint-cli
    rev: v0.38.0
    hooks:
      - id: markdownlint
        args: [--fix, --config, .markdownlint.json]
        files: \.(md|mdc)$
        description: "Auto-fix markdown formatting issues"
        stages: [commit]
        additional_dependencies: [markdownlint-cli]

  - repo: local
    hooks:
      - id: markdown-format-check
        name: Markdown Format Validation
        entry: bash -c 'echo "Checking markdown files..." && npx markdownlint --config .markdownlint.json "$@"'
        language: system
        files: \.(md|mdc)$
        stages: [commit]
        description: "Validate markdown formatting"
        pass_filenames: true

  - repo: local
    hooks:
      - id: markdown-line-length
        name: Markdown Line Length Check
        entry: bash -c '
          for file in "$@"; do
            if [[ "$file" =~ \.(md|mdc)$ ]]; then
              echo "Checking line length in $file..."
              if grep -q ".\{81,\}" "$file"; then
                echo "❌ Line length violations found in $file"
                echo "Lines exceeding 80 characters:"
                grep -n ".\{81,\}" "$file" | head -5
                exit 1
              fi
            fi
          done
        '
        language: system
        files: \.(md|mdc)$
        stages: [commit]
        description: "Check markdown line length (80 chars max)"
        pass_filenames: true

  - repo: local
    hooks:
      - id: markdown-blank-lines
        name: Markdown Blank Line Validation
        entry: bash -c '
          for file in "$@"; do
            if [[ "$file" =~ \.(md|mdc)$ ]]; then
              echo "Checking blank lines in $file..."
              # Check for multiple consecutive blank lines
              if grep -q "^$" "$file" && grep -A1 "^$" "$file" | grep -q "^$"; then
                echo "❌ Multiple consecutive blank lines found in $file"
                exit 1
              fi
              # Check for missing blank lines around headings
              if grep -B1 "^##" "$file" | grep -v "^##" | grep -v "^$" | grep -v "^--"; then
                echo "❌ Missing blank line before heading in $file"
                exit 1
              fi
            fi
          done
        '
        language: system
        files: \.(md|mdc)$
        stages: [commit]
        description: "Validate markdown blank line formatting"
        pass_filenames: true
EOF
    echo "✅ Created .pre-commit-config.yaml"
else
    echo "✅ .pre-commit-config.yaml already exists"
fi

# Install the pre-commit hooks
echo "🔗 Installing pre-commit hooks..."
pre-commit install

# Install markdownlint if not present
if ! command -v npx &> /dev/null; then
    echo "📦 Installing Node.js dependencies..."
    npm install --save-dev markdownlint-cli
else
    if ! npx markdownlint --version &> /dev/null; then
        echo "📦 Installing markdownlint-cli..."
        npm install --save-dev markdownlint-cli
    else
        echo "✅ markdownlint-cli already available"
    fi
fi

# Create a markdown auto-fix script
echo "📝 Creating markdown auto-fix script..."
cat > scripts/fix-markdown.sh << 'EOF'
#!/bin/bash

# Auto-fix markdown formatting issues
# Usage: ./scripts/fix-markdown.sh [file_or_directory]

set -e

FIX_MARKDOWN() {
    local target="$1"
    
    if [ -f "$target" ]; then
        # Fix single file
        if [[ "$target" =~ \.(md|mdc)$ ]]; then
            echo "🔧 Fixing markdown formatting in $target..."
            npx markdownlint --fix "$target" || true
        fi
    elif [ -d "$target" ]; then
        # Fix all markdown files in directory
        echo "🔧 Fixing markdown formatting in $target..."
        find "$target" -name "*.md" -o -name "*.mdc" | while read -r file; do
            echo "  Processing $file..."
            npx markdownlint --fix "$file" || true
        done
    else
        echo "❌ Target $target not found"
        exit 1
    fi
}

# Default to current directory if no target specified
TARGET="${1:-.}"
FIX_MARKDOWN "$TARGET"

echo "✅ Markdown formatting fixes applied!"
echo "💡 Run 'git diff' to see what was changed"
EOF

chmod +x scripts/fix-markdown.sh

# Create a markdown validation script
echo "📝 Creating markdown validation script..."
cat > scripts/validate-markdown.sh << 'EOF'
#!/bin/bash

# Validate markdown formatting without auto-fixing
# Usage: ./scripts/validate-markdown.sh [file_or_directory]

set -e

VALIDATE_MARKDOWN() {
    local target="$1"
    
    if [ -f "$target" ]; then
        # Validate single file
        if [[ "$target" =~ \.(md|mdc)$ ]]; then
            echo "🔍 Validating markdown formatting in $target..."
            npx markdownlint "$target"
        fi
    elif [ -d "$target" ]; then
        # Validate all markdown files in directory
        echo "🔍 Validating markdown formatting in $target..."
        find "$target" -name "*.md" -o -name "*.mdc" | while read -r file; do
            echo "  Checking $file..."
            npx markdownlint "$file" || true
        done
    else
        echo "❌ Target $target not found"
        exit 1
    fi
}

# Default to current directory if no target specified
TARGET="${1:-.}"
VALIDATE_MARKDOWN "$TARGET"

echo "✅ Markdown validation complete!"
EOF

chmod +x scripts/validate-markdown.sh

echo ""
echo "🎉 Markdown Pre-commit Hooks Setup Complete!"
echo ""
echo "📋 What was installed:"
echo "  ✅ pre-commit hooks for automatic markdown formatting"
echo "  ✅ .pre-commit-config.yaml with markdown rules"
echo "  ✅ scripts/fix-markdown.sh for manual fixes"
echo "  ✅ scripts/validate-markdown.sh for validation"
echo ""
echo "🚀 Usage:"
echo "  • Hooks run automatically on commit"
echo "  • Manual fix: ./scripts/fix-markdown.sh [file/dir]"
echo "  • Manual check: ./scripts/validate-markdown.sh [file/dir]"
echo "  • Test hooks: pre-commit run --all-files"
echo ""
echo "💡 The hooks will now automatically fix markdown issues before commits!"
