name: Markdown (Fail Fast)

on:
  push:
    paths:
      - "**.md"
  pull_request:
    paths:
      - "**.md"

permissions:
  contents: read

jobs:
  changedfiles:
    name: changed files
    runs-on: ubuntu-latest
    outputs:
      md: ${{ steps.changes.outputs.md }}
    steps:
      - name: Checkout Repo
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          # Shallow clone, but enough for `git diff HEAD~1 HEAD`.
          fetch-depth: 2
      - name: Get changed files
        id: changes
        env:
          EVENT_NAME: ${{ github.event_name }}
          BASE_SHA: ${{ github.event.pull_request.base.sha || '' }}
          HEAD_SHA: ${{ github.event.pull_request.head.sha || '' }}
        shell: bash
        run: |
          echo "Detecting changed markdown files..."

          if [[ "$EVENT_NAME" == "pull_request" ]]; then
            echo "Running in pull_request context"
            echo "Base SHA: $BASE_SHA"
            echo "Head SHA: $HEAD_SHA"
            CHANGED=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA" | grep '\.md$' || true)
          elif [[ "$EVENT_NAME" == "push" ]]; then
            echo "Running in push context"
            CHANGED=$(git diff --name-only HEAD~1 HEAD | grep '\.md$' || true)
          else
            echo "Unsupported event type: $EVENT_NAME"
            exit 1
          fi

          MD=$(echo "$CHANGED" | tr '\n' ' ' | xargs)
          echo "Markdown files changed: $MD"
          echo "md=$MD" >> "$GITHUB_OUTPUT"

  lint:
    name: lint markdown files
    runs-on: ubuntu-latest
    needs: changedfiles
    if: ${{needs.changedfiles.outputs.md}}
    steps:
      - name: Checkout Repo
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
      - name: Run linter
        uses: docker://avtodev/markdown-lint:v1@sha256:6aeedc2f49138ce7a1cd0adffc1b1c0321b841dc2102408967d9301c031949ee
        with:
          args: ${{needs.changedfiles.outputs.md}}
