name: publish-pypi

# Publish the forkd Python SDK to PyPI when a GitHub Release is
# published. Uses PyPI's Trusted Publishers (OIDC) — no API token,
# no repository secret. The trust relationship is configured on PyPI:
# Owner=deeplethe, Repository=forkd, Workflow=publish-pypi.yml,
# Environment=pypi.
#
# Trigger chain:
#   push tag v* → release.yml builds binaries + creates GitHub Release
#                 → this workflow fires on the "release published" event
#                 → sdist + wheel uploaded to https://pypi.org/p/forkd
on:
  release:
    types: [published]
  workflow_dispatch:   # let maintainers re-run a publish manually

jobs:
  publish:
    name: build + upload to PyPI
    runs-on: ubuntu-latest
    # The `release: published` event fires on every release in the
    # repo, including sibling packages with different tag prefixes
    # (e.g. `mcp-v*` for `forkd-mcp`). Skip those — only forkd's own
    # `v*` releases should publish the forkd SDK.
    if: github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v')
    environment: pypi   # must match the GitHub environment + PyPI Trusted Publisher config
    permissions:
      id-token: write   # OIDC for Trusted Publishers
      contents: read
    steps:
      - uses: actions/checkout@v4

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

      - name: Verify SDK version matches the release tag
        run: |
          ref="${GITHUB_REF_NAME#v}"
          # workflow_dispatch sets REF_NAME to the branch name; skip
          # the check there so manual re-runs aren't blocked.
          if [ "${GITHUB_EVENT_NAME}" != "workflow_dispatch" ]; then
            sdk_ver=$(grep -E '^version = ' sdk/python/pyproject.toml | head -1 | cut -d'"' -f2)
            if [ "${sdk_ver}" != "${ref}" ]; then
              echo "::error::SDK version ${sdk_ver} != release tag ${ref}"
              exit 1
            fi
          fi

      - name: Build sdist + wheel
        working-directory: sdk/python
        run: |
          python -m pip install --upgrade build
          python -m build

      - name: Publish to PyPI (Trusted Publisher)
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          packages-dir: sdk/python/dist
          print-hash: true
