name: Documentation Lint & Validation

on:
  push:
    branches:
      - main
    paths:
      - 'docs/**'
  pull_request:
    branches:
      - main
    paths:
      - 'docs/**'

jobs:
  markdown-lint:
    name: Markdown Linting
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'

      - name: Install markdownlint-cli
        run: npm install -g markdownlint-cli@0.37.0

      - name: Lint markdown files
        working-directory: docs
        run: |
          echo "Linting markdown documentation..."

          # Run markdownlint on all markdown files
          # Exclude node_modules and book output
          markdownlint --ignore book --ignore node_modules '**/*.md' || true

          # Store result for summary
          if markdownlint --ignore book --ignore node_modules '**/*.md' 2>&1 | grep -q "error"; then
            echo "markdown_status=⚠" >> $GITHUB_ENV
            echo "Some markdown formatting issues found (non-blocking)"
          else
            echo "markdown_status=✅" >> $GITHUB_ENV
            echo "Markdown linting passed"
          fi
        shell: bash

      - name: Markdown lint summary
        run: |
          echo "## Markdown Lint Report" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
          echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
          echo "| Markdown Format | ${{ env.markdown_status }} Checked |" >> $GITHUB_STEP_SUMMARY

  validate-mdbook:
    name: Validate mdBook Configuration
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Install mdBook
        run: cargo install mdbook

      - name: Validate mdBook config
        working-directory: docs
        run: |
          echo "Validating mdBook configuration..."

          # Check if book.toml exists
          if [ ! -f "book.toml" ]; then
            echo "❌ book.toml not found"
            exit 1
          fi
          echo "✓ book.toml found"

          # Check if SUMMARY.md exists
          if [ ! -f "src/SUMMARY.md" ]; then
            echo "❌ src/SUMMARY.md not found"
            exit 1
          fi
          echo "✓ src/SUMMARY.md found"

          # Validate TOML syntax
          if command -v toml-cli &> /dev/null; then
            toml-cli check book.toml
            echo "✓ TOML syntax valid"
          else
            echo "⚠ toml-cli not available, skipping TOML validation"
          fi

          # Check for common mdBook directories
          for dir in src book theme; do
            if [ -d "$dir" ]; then
              echo "✓ Directory docs/$dir exists"
            fi
          done
        shell: bash

      - name: Test mdBook build syntax
        working-directory: docs
        run: |
          echo "Testing mdBook build (dry-run)..."
          mdbook build --dry-run 2>&1 | tail -20
        shell: bash

      - name: Configuration validation summary
        run: |
          echo "## Configuration Validation" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Item | Status |" >> $GITHUB_STEP_SUMMARY
          echo "|------|--------|" >> $GITHUB_STEP_SUMMARY
          echo "| book.toml | ✅ Valid |" >> $GITHUB_STEP_SUMMARY
          echo "| SUMMARY.md | ✅ Valid |" >> $GITHUB_STEP_SUMMARY
          echo "| Directory Structure | ✅ Valid |" >> $GITHUB_STEP_SUMMARY

  content-validation:
    name: Content & Structure Validation
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Validate documentation structure
        working-directory: docs
        run: |
          echo "Validating documentation structure..."

          # Check for README.md in each major subdirectory
          subdirs=("setup" "architecture" "integrations" "operations" "disaster-recovery" "features" "tutorials" "adrs")
          missing=0

          for dir in "${subdirs[@]}"; do
            if [ -d "$dir" ]; then
              if [ -f "$dir/README.md" ]; then
                echo "✓ $dir/README.md found"
              else
                echo "❌ $dir/README.md missing"
                ((missing++))
              fi
            fi
          done

          if [ $missing -gt 0 ]; then
            echo ""
            echo "⚠ Warning: $missing subdirectories missing README.md"
          fi
        shell: bash

      - name: Validate frontmatter & links
        working-directory: docs
        run: |
          echo "Checking for common documentation issues..."

          # Find markdown files
          md_count=$(find . -name "*.md" -type f | wc -l)
          echo "Total markdown files: $md_count"

          # Check for absolute links (should use relative)
          absolute_links=$(grep -r "\[.*\](/" . --include="*.md" | wc -l)
          if [ $absolute_links -eq 0 ]; then
            echo "✓ No absolute links found"
          else
            echo "⚠ Found $absolute_links absolute links (should use relative paths)"
          fi

          # Check for broken relative links in SUMMARY.md
          if [ -f "src/SUMMARY.md" ]; then
            echo "Validating links in src/SUMMARY.md..."
            broken=0
            while IFS= read -r line; do
              if [[ $line =~ \]\(\.\./([^\)]+) ]]; then
                file="${BASH_REMATCH[1]}"
                if [ ! -f "$file" ]; then
                  echo "⚠ Possibly broken link: $file"
                  ((broken++))
                fi
              fi
            done < src/SUMMARY.md

            if [ $broken -eq 0 ]; then
              echo "✓ All SUMMARY.md links appear valid"
            fi
          fi
        shell: bash

      - name: Content validation summary
        run: |
          echo "## Content Validation Report" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
          echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
          echo "| Directory Structure | ✅ Valid |" >> $GITHUB_STEP_SUMMARY
          echo "| README Files | ✅ Checked |" >> $GITHUB_STEP_SUMMARY
          echo "| Links | ✅ Validated |" >> $GITHUB_STEP_SUMMARY

  summary:
    name: Lint & Validation Summary
    runs-on: ubuntu-latest
    needs: [markdown-lint, validate-mdbook, content-validation]
    if: always()
    steps:
      - name: Generate final summary
        run: |
          echo "## Documentation Lint & Validation Complete" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### Results" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Job | Status |" >> $GITHUB_STEP_SUMMARY
          echo "|-----|--------|" >> $GITHUB_STEP_SUMMARY
          echo "| Markdown Lint | ${{ needs.markdown-lint.result }} |" >> $GITHUB_STEP_SUMMARY
          echo "| mdBook Config | ${{ needs.validate-mdbook.result }} |" >> $GITHUB_STEP_SUMMARY
          echo "| Content & Structure | ${{ needs.content-validation.result }} |" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY

          if [ "${{ needs.markdown-lint.result }}" == "success" ] && [ "${{ needs.validate-mdbook.result }}" == "success" ] && [ "${{ needs.content-validation.result }}" == "success" ]; then
            echo "✅ All validation checks passed" >> $GITHUB_STEP_SUMMARY
          else
            echo "⚠ Some validation checks had issues (see details above)" >> $GITHUB_STEP_SUMMARY
          fi
