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@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3

      - 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@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.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']
              });
            }
