name: Documentation

on:
  push:
    branches: [main]
    paths:
      - "docs/**"
      - "scripts/publish_docs.py"
      - "scripts/validate_docs.py"
      - ".gitbook.yaml"
      - ".github/workflows/docs.yml"
  pull_request:
    paths:
      - "docs/**"
      - "scripts/publish_docs.py"
      - "scripts/validate_docs.py"
      - ".gitbook.yaml"
      - ".github/workflows/docs.yml"
  workflow_dispatch:

jobs:
  docs:
    permissions:
      contents: write
    runs-on: ubuntu-latest
    steps:
      - name: Check out the repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          fetch-depth: 0

      - name: Build GitBook site
        run: python scripts/publish_docs.py

      - name: Validate site output
        run: python scripts/validate_docs.py

      - name: Deploy to gitbook-docs branch
        if: "${{ github.event_name == 'push' || github.event_name == 'workflow_dispatch' }}"
        run: |
          git config user.name 'github-actions[bot]'
          git config user.email 'github-actions[bot]@users.noreply.github.com'
          cp .gitbook-branch-readme.md site/README-BRANCH.md

          # Move site/ outside the repo before switching branches
          mv site/ /tmp/gitbook-site/

          git fetch origin gitbook-docs || true
          if git rev-parse --verify origin/gitbook-docs >/dev/null 2>&1; then
            git checkout gitbook-docs
          else
            git checkout --orphan gitbook-docs
            git rm -rf .
          fi

          rsync -a --delete --exclude='.git' /tmp/gitbook-site/ .
          git add -A
          if ! git diff --cached --quiet; then
            git commit -m "docs: update GitBook documentation from ${{ github.sha }}"
            git push origin gitbook-docs
          fi
