name: Build Docs
on:
  push:
    branches:
      - main
  pull_request:
    types:
      - opened
      - synchronize

env:
  UV_SYSTEM_PYTHON: 1


jobs:
  changes:
    runs-on: ubuntu-latest
    # Required permissions
    permissions:
      pull-requests: read
    # Set job outputs to values from filter step
    outputs:
      docs: ${{ steps.filter.outputs.docs }}
    steps:
    - uses: actions/checkout@v4
    # For pull requests it's not necessary to checkout the code but for the main branch it is
    - uses: dorny/paths-filter@v3
      id: filter
      with:
        filters: |
          docs:
            - README.md
            - docs/**
            - docs_src/**
            - requirements-docs.txt
            - requirements-docs-insiders.txt
            - pyproject.toml
            - mkdocs.yml
            - mkdocs.insiders.yml
            - mkdocs.maybe-insiders.yml
            - mkdocs.no-insiders.yml
            - .github/workflows/build-docs.yml
            - .github/workflows/deploy-docs.yml
            - data/**

  build-docs:
    needs:
      - changes
    if: ${{ needs.changes.outputs.docs == 'true' }}
    runs-on: ubuntu-latest
    steps:
      - name: Dump GitHub context
        env:
          GITHUB_CONTEXT: ${{ toJson(github) }}
        run: echo "$GITHUB_CONTEXT"
      - uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"
      - name: Setup uv
        uses: astral-sh/setup-uv@v5
        with:
          version: "0.4.15"
          enable-cache: true
          cache-dependency-glob: |
            requirements**.txt
            pyproject.toml
      - name: Install docs extras
        run: uv pip install -r requirements-docs.txt
      - name: Install Material for MkDocs Insiders
        if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' )
        run: uv pip install -r requirements-docs-insiders.txt
        env:
          TOKEN: ${{ secrets.SQLMODEL_MKDOCS_MATERIAL_INSIDERS }}
      - uses: actions/cache@v4
        with:
          key: mkdocs-cards-${{ github.ref }}
          path: .cache
      - name: Verify README
        run: python ./scripts/docs.py verify-readme
      - name: Build Docs
        run: python ./scripts/docs.py build
      - uses: actions/upload-artifact@v4
        with:
          name: docs-site
          path: ./site/**
          include-hidden-files: true

  # https://github.com/marketplace/actions/alls-green#why
  docs-all-green:  # This job does nothing and is only used for the branch protection
    if: always()
    needs:
      - build-docs
    runs-on: ubuntu-latest
    steps:
      - name: Decide whether the needed jobs succeeded or failed
        uses: re-actors/alls-green@release/v1
        with:
          jobs: ${{ toJSON(needs) }}
          allowed-skips: build-docs
