# Workflow that checks MDX format in docs/ folder
name: MDX Lint

# Run on pushes to main and on pull requests that modify docs/ files
on:
  push:
    branches:
      - main
    paths:
      - 'docs/**/*.mdx'
  pull_request:
    paths:
      - 'docs/**/*.mdx'

# If triggered by a PR, it will be in the same group. However, each commit on main will be in its own unique group
concurrency:
  group: ${{ github.workflow }}-${{ (github.head_ref && github.ref) || github.run_id }}
  cancel-in-progress: true

jobs:
  mdx-lint:
    name: Lint MDX files
    runs-on: blacksmith-4vcpu-ubuntu-2204
    steps:
      - uses: actions/checkout@v4

      - name: Install Node.js 22
        uses: useblacksmith/setup-node@v5
        with:
          node-version: 22

      - name: Install MDX dependencies
        run: |
          npm install @mdx-js/mdx@3 glob@10

      - name: Validate MDX files
        run: |
          node -e "
          const {compile} = require('@mdx-js/mdx');
          const fs = require('fs');
          const path = require('path');
          const glob = require('glob');

          async function validateMDXFiles() {
            const files = glob.sync('docs/**/*.mdx');
            console.log('Found', files.length, 'MDX files to validate');

            let hasErrors = false;

            for (const file of files) {
              try {
                const content = fs.readFileSync(file, 'utf8');
                await compile(content);
                console.log('✅ MDX parsing successful for', file);
              } catch (err) {
                console.error('❌ MDX parsing failed for', file, ':', err.message);
                hasErrors = true;
              }
            }

            if (hasErrors) {
              console.error('\\n❌ Some MDX files have parsing errors. Please fix them before merging.');
              process.exit(1);
            } else {
              console.log('\\n✅ All MDX files are valid!');
            }
          }

          validateMDXFiles();
          "
