name: Build and upload to PyPI

on:
  release:
    types: 
      - published

jobs:

  build-artifacts:
    
    runs-on: ubuntu-latest

    steps:

      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
      
      - name: Install Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.11"

      - name: Install PyPi dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install build twine
      
      - name: Build tarball and wheels
        run: |
          git clean -xdf
          git restore -SW .
          python -m build
      
      - name: Upload artifact
        uses: actions/upload-artifact@v3
        with:
          name: releases
          path: dist
  
  publish_pypi_test:
    
    needs: build-artifacts
    runs-on: ubuntu-latest
    environment:
      name: release
      url: https://test.pypi.org/project/acs-axiom
    permissions:
      id-token: write
    
    steps:
    
      - name: Install Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.11"

      - name: Download artifact
        uses: actions/download-artifact@v3
        with:
          name: releases
          path: dist
      
      - name: Install PyPi dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install build twine

      - name: Check build artifacts
        run: |
          python -m twine check dist/*
          pwd
          if [ -f dist/acs-axiom-0.0.0.tar.gz ]; then
            echo "INVALID VERSION NUMBER"
            exit 1
          fi

      - name: Publish package distributions to TestPyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          repository-url: https://test.pypi.org/legacy/

  publish_pypi_prod:
      
      needs: publish_pypi_test
      runs-on: ubuntu-latest
      environment:
        name: release
        url: https://pypi.org/project/acs-axiom
      permissions:
        id-token: write
      
      steps:
      
        - name: Install Python
          uses: actions/setup-python@v4
          with:
            python-version: "3.11"

        - name: Download artifact
          uses: actions/download-artifact@v3
          with:
            name: releases
            path: dist
        
        - name: Install PyPi dependencies
          run: |
            python -m pip install --upgrade pip
            python -m pip install build twine

        - name: Check build artifacts
          run: |
            python -m twine check dist/*
            pwd
            if [ -f dist/acs-axiom-0.0.0.tar.gz ]; then
              echo "INVALID VERSION NUMBER"
              exit 1
            fi

        - name: Publish package distributions to PyPi
          uses: pypa/gh-action-pypi-publish@release/v1