
name: Documentation build and deploy

on:
  push:
     branches: [ master ]
     tags: ['*']
  pull_request:
     branches: [ master ]
  workflow_dispatch:

concurrency: 
  group: ci-docs-${{ github.ref }}
  cancel-in-progress: true


jobs:
  build-latest:
    runs-on: ubuntu-latest
    if: github.repository == 'anybody/ammr' || github.event_name != 'push'
  
    steps:
      - uses: actions/checkout@v4
        
      - uses: prefix-dev/setup-pixi@v0.8.7
        with:
          environments: docs
          cache-write: ${{ github.event_name == 'push' && github.ref_name == 'master' }}
          activate-environment: docs
  
      - name: Link check
        run: |
          cd Docs
          sphinx-build -M linkcheck . _build -W --keep-going -a -q 
                            
      - name: Build Documentation
        run: |
          cd Docs
          rm -rf _build
          sphinx-build -M html . _build -W --keep-going -a -t draft

      - uses: actions/upload-artifact@v4
        with:
          name: beta-version
          path: Docs/_build/html

    
  build-tagged:
    runs-on: ubuntu-latest
    if: (github.repository == 'anybody/ammr' || github.event_name != 'push') && github.ref == 'refs/heads/master'
  
    steps:
      - uses: actions/checkout@v4
        with: 
          fetch-depth: 0
          

      - name: Checkout last tagged version
        run: |
          git checkout $(git describe --tags `git rev-list --tags=ammr* --max-count=1`);
      
      - uses: prefix-dev/setup-pixi@v0.8.7
        with:
            environments: docs
            cache-write: ${{ github.event_name == 'push' && github.ref_name == 'master' }}
            activate-environment: docs
  
      - name: Build Documentation
        run: |
          cd Docs
          sphinx-build -M html . _build -a

      - uses: actions/upload-artifact@v4
        with:
          name: tagged-version
          path: Docs/_build/html


  prepare-pages:
    needs: [build-latest, build-tagged]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: tagged-version
          path: public
      - uses: actions/download-artifact@v4
        with:
          name: beta-version
          path: public/beta
      - uses: actions/upload-pages-artifact@v3
        with: 
          path: public


  deploy:
    needs: prepare-pages
    if: github.ref == 'refs/heads/master'
    runs-on: ubuntu-latest
    permissions:
      pages: write    
      id-token: write 

    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}

    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
          
