name: '🔗 Check Broken Links'

on:
  push:
    branches: ['main']
    paths:
      - '**.md'
      - 'docs/**'
  pull_request:
    branches: ['main']
    paths:
      - '**.md'
      - 'docs/**'
  schedule:
    - cron: '0 0 * * 0'
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: 'read'
  issues: 'write'

jobs:
  check-links:
    runs-on: 'ubuntu-latest'
    timeout-minutes: 15
    steps:
      - name: 'Checkout'
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: 'Check for broken links'
        uses: lycheeverse/lychee-action@8646ba30535128ac92d33dfc9133794bfdd9b411 # v2.8.0
        with:
          args: >-
            --verbose
            --no-progress
            --exclude '^https://github.com/.*/issues/new'
            --exclude '^https://github.com/.*/compare/'
            --exclude 'localhost'
            --exclude '127.0.0.1'
            --exclude 'file://'
            --exclude 'npmjs.com'
            --exclude 'unrealengine.com'
            --exclude 'rustwasm.github.io'
            --exclude 'github.com/modelcontextprotocol/sdk'

            '**/*.md'
            'docs/**'
          fail: true

      - name: 'Create issue on failure'
        if: failure() && github.event_name == 'schedule'
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
        with:
          github-token: '${{ secrets.GITHUB_TOKEN }}'
          script: |
            const title = '🔗 Broken links detected in documentation';
            const body = `The weekly link check found broken links in the documentation.
            
            Please review the [workflow run](${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}) for details.`;
            
            const { data: issues } = await github.rest.issues.listForRepo({
              owner: context.repo.owner,
              repo: context.repo.repo,
              state: 'open',
              labels: 'area/docs'
            });
            
            const existingIssue = issues.find(i => i.title === title);
            if (!existingIssue) {
              await github.rest.issues.create({
                owner: context.repo.owner,
                repo: context.repo.repo,
                title: title,
                body: body,
                labels: ['area/docs', 'type/bug']
              });
            }
