name: Publish Python 🐍 distribution to PyPI

on:
  push:
    branches:
      - master
    tags:
      - 'v*.*.*'
  workflow_dispatch:

permissions:
  contents: read
  id-token: write  # required for OIDC trusted publishing

jobs:
  build:
    name: Build distribution
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # full history so hatch-vcs can read tags

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Install build tools
        run: |
          python -m pip install --upgrade pip
          pip install hatch hatch-vcs

      - name: Build package
        run: hatch build

      - name: Store distribution artifacts
        uses: actions/upload-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

  publish-to-testpypi:
    name: Publish to TestPyPI
    if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/')
    needs: build
    runs-on: ubuntu-latest
    environment:
      name: testpypi
      url: https://test.pypi.org/p/nmn
    steps:
      - name: Download distribution artifacts
        uses: actions/download-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

      - name: Publish to TestPyPI (trusted publisher / OIDC)
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          repository-url: https://test.pypi.org/legacy/
          skip-existing: true

  publish-to-pypi:
    name: Publish to PyPI
    if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/')
    needs: [build, publish-to-testpypi]
    runs-on: ubuntu-latest
    environment:
      name: pypi
      url: https://pypi.org/p/nmn
    steps:
      - name: Download distribution artifacts
        uses: actions/download-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

      - name: Publish to PyPI (trusted publisher / OIDC)
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          skip-existing: true
