name: Publish Python Package

on:
  release:
    types: [created]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.11"
          cache: 'pip'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip setuptools wheel
          pip install build

      - name: Build package
        run: python -m build

      - name: Check if version exists
        id: check_version
        run: |
          VERSION=$(python setup.py --version)
          echo "Checking version: $VERSION"
          if curl -s "https://pypi.org/pypi/jax-dataloaders/$VERSION/json" > /dev/null; then
            echo "Version $VERSION already exists on PyPI"
            echo "exists=true" >> $GITHUB_OUTPUT
          else
            echo "Version $VERSION is new"
            echo "exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Upload built package
        uses: actions/upload-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

  publish:
    needs: build
    runs-on: ubuntu-latest
    if: needs.build.outputs.check_version.exists == 'false'
    permissions:
      id-token: write
    steps:
      - name: Download built package
        uses: actions/download-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          repository_url: https://pypi.org/legacy/

  handle-version-conflict:
    needs: build
    runs-on: ubuntu-latest
    if: needs.build.outputs.check_version.exists == 'true'
    steps:
      - name: Handle version conflict
        run: |
          echo "Error: Version $(python setup.py --version) already exists on PyPI"
          echo "Please update the version in setup.py and try again"
          exit 1
