name: Publish to PyPI

on:
  push:
    tags:
      - 'v*'  # Trigger on version tags like v1.2.0
  workflow_dispatch:  # Allow manual trigger for testing

jobs:
  build_wheels:
    name: Build wheels on ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest]

    steps:
      - uses: actions/checkout@v4
        with:
          submodules: 'recursive'
          fetch-depth: 0  # Fetch all history for setuptools-scm
          fetch-tags: true  # Explicitly fetch tags

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

      - name: Install cibuildwheel
        run: python -m pip install cibuildwheel==2.16.2

      - name: Build wheels
        run: python -m cibuildwheel --output-dir wheelhouse
        env:
          # Build for Python 3.8, 3.9, 3.10, 3.11, 3.12
          CIBW_BUILD: cp38-* cp39-* cp310-* cp311-* cp312-*
          # Skip 32-bit builds and musllinux for now
          CIBW_SKIP: "*-win32 *-manylinux_i686 *-musllinux_*"
          # Pass CMake arguments for building Python module
          CIBW_ENVIRONMENT: >
            CMAKE_ARGS="-DBUILDPYTHONMODULE=ON -DNOMPI=ON"

      - uses: actions/upload-artifact@v4
        with:
          name: wheels-${{ matrix.os }}
          path: ./wheelhouse/*.whl

  build_sdist:
    name: Build source distribution
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: 'recursive'
          fetch-depth: 0  # Fetch all history for setuptools-scm
          fetch-tags: true  # Explicitly fetch tags

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

      - name: Verify git tags (debug)
        run: |
          git describe --tags --always
          git tag -l "v*" | tail -5

      - name: Install build dependencies
        run: python -m pip install build

      - name: Build sdist
        run: python -m build --sdist

      - uses: actions/upload-artifact@v4
        with:
          name: sdist
          path: dist/*.tar.gz

  publish_to_pypi:
    name: Publish to PyPI
    needs: [build_wheels, build_sdist]
    runs-on: ubuntu-latest
    permissions:
      id-token: write  # Required for trusted publishing

    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: dist
          merge-multiple: true

      - name: Display structure of downloaded files
        run: ls -R dist

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          password: ${{ secrets.PYPI_API_TOKEN }}
          skip-existing: true
