name: Documentation

on:
  push:
    branches: [ main ]
    paths:
      - 'docs/**'
      - 'src/**'
      - 'mkdocs.yml'
      - '.github/workflows/docs.yml'
  pull_request:
    branches: [ main ]
    paths:
      - 'docs/**'
      - 'src/**'
      - 'mkdocs.yml'

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: "3.11"

    - name: Cache pip dependencies
      uses: actions/cache@v3
      with:
        path: ~/.cache/pip
        key: ${{ runner.os }}-docs-${{ hashFiles('**/pyproject.toml') }}
        restore-keys: |
          ${{ runner.os }}-docs-

    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -e ".[docs]"

    - name: Configure Git for mkdocs
      run: |
        git config --global user.name "github-actions[bot]"
        git config --global user.email "github-actions[bot]@users.noreply.github.com"

    - name: Build documentation
      run: |
        mkdocs build --clean --strict

    - name: Upload documentation artifacts
      uses: actions/upload-artifact@v3
      with:
        name: documentation
        path: site/

    - name: Setup Pages
      if: github.ref == 'refs/heads/main' && github.event_name == 'push'
      uses: actions/configure-pages@v3

    - name: Upload to GitHub Pages
      if: github.ref == 'refs/heads/main' && github.event_name == 'push'
      uses: actions/upload-pages-artifact@v2
      with:
        path: site/

  deploy:
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
    - name: Deploy to GitHub Pages
      id: deployment
      uses: actions/deploy-pages@v2

  link-check:
    runs-on: ubuntu-latest
    needs: build
    steps:
    - uses: actions/checkout@v4

    - name: Download documentation artifacts
      uses: actions/download-artifact@v3
      with:
        name: documentation
        path: site/

    - name: Check documentation links
      uses: lycheeverse/lychee-action@v1.8.0
      with:
        args: --verbose --no-progress 'site/**/*.html'
        fail: true
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
