name: GitHub Pages Redirects

on:
  push:
    branches: [main]
    paths:
      - "docs/**"
      - "scripts/publish_docs.py"
      - "scripts/validate_docs.py"
      - "scripts/generate_github_pages_redirects.py"
      - "tests/docs/**"
      - ".github/workflows/pages-redirect.yml"
  pull_request:
    paths:
      - "docs/**"
      - "scripts/publish_docs.py"
      - "scripts/validate_docs.py"
      - "scripts/generate_github_pages_redirects.py"
      - "tests/docs/**"
      - ".github/workflows/pages-redirect.yml"
  workflow_dispatch:

jobs:
  redirect-site:
    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: Set up Python
        uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
        with:
          python-version: "3.11"

      - name: Run redirect generator tests
        run: python -m unittest discover -s tests/docs -p 'test_*.py'

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

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

      - name: Build GitHub Pages redirects
        run: python scripts/generate_github_pages_redirects.py

      - name: Upload generated redirect site as PR artifact
        if: github.event_name == 'pull_request'
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: github-pages-redirect-preview
          path: gh-pages-redirect/

      - name: Deploy to gh-pages 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'

          mv gh-pages-redirect/ /tmp/gh-pages-redirect/

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

          rsync -a --delete --exclude='.git' /tmp/gh-pages-redirect/ .
          git add -A
          if ! git diff --cached --quiet; then
            git commit -m "docs: update GitHub Pages redirects from ${{ github.sha }}"
            git push origin gh-pages
          fi
