name: PyPI Release

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      publish:
        description: 'Publish to PyPI (true/false)'
        required: true
        default: 'false'

permissions:
  contents: read

jobs:
  build-wheels:
    name: Build wheels (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: macos-latest
            target: aarch64-apple-darwin
          - os: windows-latest
            target: x86_64-pc-windows-msvc

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install maturin
        run: pip install maturin

      - name: Build wheels
        run: maturin build --release --target ${{ matrix.target }} --out dist

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

  build-sdist:
    name: Build source distribution
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install maturin
        run: pip install maturin

      - name: Build sdist
        run: maturin sdist --out dist

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

  publish:
    name: Publish to PyPI
    needs: [build-wheels, build-sdist]
    runs-on: ubuntu-latest
    if: github.event_name == 'release' || github.event.inputs.publish == 'true'
    environment:
      name: pypi
      url: https://pypi.org/project/shodh-memory/

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

      - name: List artifacts
        run: ls -la dist/

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