name: ci-docs

on:
  push:
    branches:
      - main
    tags:
      - "*.*.*"
  pull_request:
    branches:
      - main
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true

jobs:
  build:
    if: github.repository_owner == 'xonsh'
    runs-on: ubuntu-latest
    env:
      UV_SYSTEM_PYTHON: 1
    name: Xonsh docs to gh-pages
    steps:
      - uses: actions/checkout@v7
      - name: Setup Python
        uses: actions/setup-python@v7
        with:
          python-version: "3.13"
      - uses: astral-sh/setup-uv@v7
        with:
          enable-cache: true
      - run: uv pip install --system -e '.[doc]'
      - name: restore timestamps
        uses: chetan/git-restore-mtime-action@v2
      - name: Cache build and autosummary
        uses: actions/cache@v6
        with:
          path: |
            docs/_build
            docs/api/_autosummary
          key: docs-${{ runner.os }}-${{ github.ref }}
          restore-keys: |
            docs-${{ runner.os }}-refs/heads/main
            docs-${{ runner.os }}-
      - name: Build Docs
        run: cd docs && make html
      - uses: tibdex/github-app-token@v2
        if: ${{ github.event_name != 'pull_request' }}
        id: generate-token
        with:
          app_id: ${{ secrets.APP_ID }}
          private_key: ${{ secrets.APP_PRIVATE_KEY }}
          repository: xonsh/xonsh-docs
      - name: Deploy to dev if not tagged
        if: github.event_name != 'pull_request' && !startsWith(github.ref, 'refs/tags/')
        uses: peaceiris/actions-gh-pages@v4
        with:
          personal_token: ${{ steps.generate-token.outputs.token }}
          external_repository: xonsh/xonsh-docs
          publish_dir: ./docs/_build/html
          destination_dir: dev # latest as in main branch
      - name: Deploy to stable if tagged
        if: github.event_name != 'pull_request' && startsWith(github.ref, 'refs/tags/')
        uses: peaceiris/actions-gh-pages@v4
        with:
          personal_token: ${{ steps.generate-token.outputs.token }}
          external_repository: xonsh/xonsh-docs
          publish_dir: ./docs/_build/html
          cname: xon.sh
#          # todo: implement versioned docs
