name: Wheels

# Binary wheels (manylinux_2_28 x86_64, win_amd64, macOS 14+ arm64/x86_64; CPython 3.10-3.14)
# and an sdist.
# cibuildwheel is configured in pyproject.toml ([tool.cibuildwheel]); every wheel is tested
# with the pytest suite before it is uploaded as an artifact. For a v* tag the release job then
# creates the GitHub release with the wheels, the sdist and the tag's CHANGELOG section; an
# existing tag can be (re)released by running the workflow manually with `release_tag`.

on:
  push:
    tags: ["v*"]
  workflow_dispatch:
    inputs:
      release_tag:
        description: "Existing tag (e.g. v0.16.0) to build from and publish as a GitHub release"
        required: false
        default: ""
  # Only packaging changes trigger wheel builds on PRs. Source changes (incl. CMakeLists.txt,
  # which nearly every feature PR touches) are built and tested on both platforms by ci.yml;
  # wheels are built for tags and on demand (workflow_dispatch).
  pull_request:
    paths:
      - pyproject.toml
      - .github/workflows/wheels.yml

permissions:
  contents: read

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

jobs:
  wheels:
    name: Wheels (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
    steps:
      - uses: actions/checkout@v5
        with:
          ref: ${{ inputs.release_tag || github.ref }}
      - name: Build and test wheels
        uses: pypa/cibuildwheel@v3.2.1
        with:
          output-dir: wheelhouse
      - uses: actions/upload-artifact@v7
        with:
          name: wheels-${{ matrix.os }}
          path: wheelhouse/*.whl
          if-no-files-found: error

  sdist:
    name: Source distribution
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
        with:
          ref: ${{ inputs.release_tag || github.ref }}
      - uses: actions/setup-python@v6
        with:
          python-version: "3.12"
      - name: Build sdist
        run: |
          python -m pip install --upgrade build twine
          python -m build --sdist --outdir dist
          python -m twine check dist/*
      - uses: actions/upload-artifact@v7
        with:
          name: sdist
          path: dist/*.tar.gz
          if-no-files-found: error

  manual:
    name: User manual (PDF)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
        with:
          ref: ${{ inputs.release_tag || github.ref }}
      - uses: actions/setup-python@v6
        with:
          python-version: "3.12"
      - name: TeX Live
        run: |
          sudo apt-get update
          sudo apt-get install -y --no-install-recommends latexmk lmodern texlive-latex-recommended \
            texlive-latex-extra texlive-fonts-recommended
      - name: Build the manual from the tagged sources
        run: |
          python -m pip install ".[mesh]"
          python docs/manual/build.py
          cp python/nurbforge/REFERENCE.md docs/manual/build/nurbforge-reference.md
      - uses: actions/upload-artifact@v7
        with:
          name: manual
          path: |
            docs/manual/build/nurbforge-manual.pdf
            docs/manual/build/nurbforge-reference.md
          if-no-files-found: error

  release:
    name: GitHub release
    needs: [wheels, sdist, manual]
    if: >-
      startsWith(github.ref, 'refs/tags/v') ||
      (github.event_name == 'workflow_dispatch' && inputs.release_tag != '')
    runs-on: ubuntu-latest
    permissions:
      contents: write
    env:
      TAG: ${{ inputs.release_tag || github.ref_name }}
      GH_TOKEN: ${{ github.token }}
    steps:
      - uses: actions/checkout@v5
        with:
          ref: ${{ inputs.release_tag || github.ref }}
      - uses: actions/download-artifact@v5
        with:
          path: dist
          merge-multiple: true
      - name: Release notes from CHANGELOG.md
        run: |
          python3 - <<'PY'
          import os, re
          version = os.environ["TAG"].removeprefix("v")
          text = open("CHANGELOG.md", encoding="utf-8").read()
          m = re.search(r"^## \[" + re.escape(version) + r"\][^\n]*\n(.*?)(?=^## \[)", text, re.S | re.M)
          notes = m.group(1).strip() if m else f"Nurbforge {version}"
          notes += ("\n\n### Install\n```bash\npip install nurbforge          # from PyPI; "
                    "nurbforge[mesh] adds gmsh\n```\nBinary wheels for Linux (manylinux_2_28 "
                    "x86_64), Windows (win_amd64) and macOS 14+ (arm64, x86_64), CPython "
                    "3.10-3.14, and the sdist are also attached below.\n\n### Documentation\n"
                    "`nurbforge-manual.pdf`: the user manual with the complete command reference "
                    "of this version.\n`nurbforge-reference.md`: the compact API reference for "
                    "language models and coding agents (also `python -m nurbforge`).\n")
          open("notes.md", "w", encoding="utf-8").write(notes)
          PY
      - name: Create or update the release
        run: |
          ls -l dist
          if gh release view "$TAG" > /dev/null 2>&1; then
            gh release upload "$TAG" dist/* --clobber
            gh release edit "$TAG" --notes-file notes.md
          else
            gh release create "$TAG" dist/* --verify-tag --title "Nurbforge ${TAG#v}" --notes-file notes.md
          fi

  # PyPI via trusted publishing (OIDC, no API token): the publisher is registered on PyPI for
  # PhotonPower/Nurbforge, workflow wheels.yml, environment "pypi". Only tag pushes publish.
  publish:
    name: Publish to PyPI
    needs: [wheels, sdist]
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    environment:
      name: pypi
      url: https://pypi.org/p/nurbforge
    permissions:
      id-token: write
    steps:
      - uses: actions/download-artifact@v5
        with:
          path: dist
          merge-multiple: true
      - name: Keep only wheels and sdist (manual and agent reference go to the GitHub release only)
        run: |
          find dist -type f ! -name '*.whl' ! -name '*.tar.gz' -delete
          ls -l dist
      - uses: pypa/gh-action-pypi-publish@release/v1
