name: Python Dist

on:
  push:
    tags:
      - "pymongocrypt-[0-9]+.[0-9]+.[0-9]+"
      - "pymongocrypt-[0-9]+.[0-9]+.[0-9]+.post[0-9]+"
      - "pymongocrypt-[0-9]+.[0-9]+.[0-9]+[a-b][0-9]+"
      - "pymongocrypt-[0-9]+.[0-9]+.[0-9]+rc[0-9]+"
  pull_request:
    paths:
      - bindings/python/*
      - bindings/python/**/*.py
      - .github/workflows/*python.yml
  workflow_dispatch:
  workflow_call:
    inputs:
      ref:
        required: true
        type: string

concurrency:
  group: python-dist-${{ github.ref }}
  cancel-in-progress: true

defaults:
  run:
    working-directory: ./bindings/python
    shell: bash -eux {0}

jobs:
  build_dist:
    if: github.repository_owner == 'mongodb' || (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call')
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
      fail-fast: false

    steps:  
      - name: Checkout libmongocrypt
        uses: actions/checkout@v5
        with:
          fetch-depth: 0
          ref: ${{ inputs.ref }}
          persist-credentials: false

      - uses: actions/setup-python@v6
        with:
          python-version: "3.9"
          cache: 'pip'
          cache-dependency-path: 'bindings/python/pyproject.toml'
          allow-prereleases: true

      - name: Build and test dist files
        run: |
          export LIBMONGOCRYPT_VERSION=$(cat ./scripts/libmongocrypt-version.txt)
          git fetch origin $LIBMONGOCRYPT_VERSION
          bash ./scripts/release.sh

      - uses: actions/upload-artifact@v4
        with:
          name: dist-${{ matrix.os }}
          path: ./bindings/python/dist/*.*
          if-no-files-found: error

  collect_dist:
    runs-on: ubuntu-latest
    needs: [build_dist]
    name: Collect dist files
    steps:
      - name: Download all workflow run artifacts
        uses: actions/download-artifact@v5
      - name: Flatten directory
        working-directory: .
        run: |
          find . -mindepth 2 -type f -exec mv {} . \;
          find . -type d -empty -delete
      - uses: actions/upload-artifact@v4
        with:
          name: all-dist-${{ github.run_id }}
          path: "./*"
