name: Release to PyPI

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:
    inputs:
      tag:
        description: "Tag to release (e.g. v0.4.1)"
        required: true

permissions:
  contents: read

jobs:
  build:
    name: Build distribution
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v6
        with:
          ref: ${{ inputs.tag || github.ref }}
          fetch-depth: 0

      - name: Install uv
        uses: astral-sh/setup-uv@v7
        with:
          python-version: "3.12"

      - uses: pnpm/action-setup@v5
        with:
          version: 10

      - uses: actions/setup-node@v6
        with:
          node-version: 20
          cache: pnpm
          cache-dependency-path: js/pnpm-lock.yaml

      - name: Build JS
        run: |
          cd js
          pnpm install
          pnpm build

      - name: Build sdist and wheel
        run: uv build

      - name: Check distribution
        run: |
          uv sync --frozen --dev
          uv run twine check dist/*

      - uses: actions/upload-artifact@v7
        with:
          name: dist
          path: dist/

  publish-testpypi:
    name: Publish to TestPyPI
    needs: build
    runs-on: ubuntu-latest
    environment: testpypi
    permissions:
      id-token: write

    steps:
      - uses: actions/download-artifact@v8
        with:
          name: dist
          path: dist/

      - name: Publish to TestPyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          repository-url: https://test.pypi.org/legacy/

  publish-pypi:
    name: Publish to PyPI
    needs: publish-testpypi
    runs-on: ubuntu-latest
    environment: pypi
    permissions:
      id-token: write

    steps:
      - uses: actions/download-artifact@v8
        with:
          name: dist
          path: dist/

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
