name: Build and Deploy Sphinx Docs

on:
  push:
    branches: ["main"]
    paths:
      - "docs/**"
  pull_request:
    branches: ["main"]
    paths:
      - "docs/**"
  workflow_dispatch:

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

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install dependencies
        run: |
          pip install -r docs/requirements.txt

      - name: Build Sphinx
        run: |
          sphinx-build -b html docs/zh docs/_build/html/zh
          sphinx-build -b html docs/en docs/_build/html/en

          printf '%s\n' \
            '<!DOCTYPE html>' \
            '<html>' \
            '  <head>' \
            '    <meta charset="utf-8" />' \
            '    <meta http-equiv="refresh" content="0; url=zh/index.html" />' \
            '    <script>window.location.href="zh/index.html"+window.location.search+window.location.hash;</script>' \
            '    <title>Redirecting...</title>' \
            '  </head>' \
            '  <body>' \
            '    <a href="zh/index.html">Redirecting...</a>' \
            '  </body>' \
            '</html>' \
            > docs/_build/html/index.html

          touch docs/_build/html/.nojekyll

      - name: Setup Pages
        uses: actions/configure-pages@v5

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: docs/_build/html

  deploy:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    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@v4
