name: User Guide Generator

on:
  push:
    branches:
      - doc
      - main
    tags:
      - 'v*'
    paths:
      - 'doc/**'
      - 'mkdocs.yml'
      - '.github/workflows/docs.yml'

permissions:
  contents: write

concurrency:
  group: "docs-${{ github.ref }}"
  cancel-in-progress: false

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

      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.x'

      - name: Install dependencies
        run: |
          pipx install mkdocs
          pipx inject mkdocs mkdocs-material
          pipx inject mkdocs pymdown-extensions
          pipx inject mkdocs mkdocs-callouts
          pipx inject mkdocs mike
          pipx inject mkdocs mkdocs-to-pdf
          pipx inject mkdocs mkdocs-glightbox
          # Workaround, if pipx inject fails to install symlink
          ln -s "$(pipx environment -V PIPX_LOCAL_VENVS)/mkdocs/bin/mike" \
                "$(pipx environment -V PIPX_BIN_DIR)/mike" || true

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

      - name: Deploy dev version
        if: github.event_name == 'push' && (github.ref == 'refs/heads/doc' || github.ref == 'refs/heads/main')
        run: |
          mike deploy --push --update-aliases dev latest
          mike set-default --push latest

      - name: Deploy tagged version
        if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
        run: |
          TAG=${GITHUB_REF#refs/tags/v}
          # Extract YEAR.MONTH from tag (e.g., v25.06.0-beta1 -> 25.06)
          VERSION=$(echo $TAG | sed -E 's/^([0-9]+\.[0-9]+)(\.[0-9]+)?(-.*)?$/\1/')
          echo "Deploying tag $TAG as docs version $VERSION"
          mike deploy --push --update-aliases $VERSION latest
          mike set-default --push latest
