# This workflow publishes a build to PyPI.
# https://packaging.python.org/en/latest/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/

name: Publish Python distribution to PyPI and TestPyPI

on:
  release:
    types: [released]

jobs:
  test:
    # Only publish if we actually pass software tests.
    # This should block us from submitting a broken build.
    uses: ./.github/workflows/pytest.yaml
  build:
    name: Build distribution
    needs: test
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4
      with:
        persist-credentials: false
        #fetch-tags: true This seemed to cause errors?
        # HEAD should have a tag if we just published, so don't need fetch: 0.
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: "3.x"
    - name: Install pypa/build
      run: >-
        python3 -m
        pip install
        build
        --user
    - name: Build a binary wheel and a source tarball
      run: python3 -m build
    - name: Store the distribution packages
      uses: actions/upload-artifact@v4
      with:
        name: python-package-distributions
        path: dist/

  publish-to-pypi:
    name: >-
      Publish Python distribution to PyPI
    needs:
    - build
    runs-on: ubuntu-latest
    environment:
      name: pypi
      url: https://pypi.org/p/molecular_dynamics_toy
    permissions:
      id-token: write  # IMPORTANT: mandatory for trusted publishing

    steps:
    - name: Download all the dists
      uses: actions/download-artifact@v4
      with:
        name: python-package-distributions
        path: dist/
    - name: Publish distribution to PyPI
      uses: pypa/gh-action-pypi-publish@release/v1
  
  publish-to-testpypi:
    # The idea is that we run testpypi first,
    # then I manually approve the pypi workflow once I confirm it worked.
    name: Publish Python distribution to TestPyPI
    needs:
    - build
    runs-on: ubuntu-latest

    environment:
      name: testpypi
      url: https://test.pypi.org/p/molecular_dynamics_toy

    permissions:
      id-token: write  # IMPORTANT: mandatory for trusted publishing

    steps:
    - name: Download all the dists
      uses: actions/download-artifact@v4
      with:
        name: python-package-distributions
        path: dist/
    - name: Publish distribution to TestPyPI
      uses: pypa/gh-action-pypi-publish@release/v1
      with:
        repository-url: https://test.pypi.org/legacy/
        verbose: true
