name: Uforia Terminal Release

on:
  push:
    branches:
      - main
      - master
    tags:
      - "v*"
  workflow_dispatch:

jobs:
  test-and-build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.11"
      - uses: astral-sh/setup-uv@v6
      - name: Stamp package version
        shell: bash
        run: |
          python - <<'PY'
          import pathlib
          import re
          import os

          path = pathlib.Path("pyproject.toml")
          text = path.read_text()
          match = re.search(r'^version = "([^"]+)"$', text, re.MULTILINE)
          if not match:
              raise SystemExit("Could not find static version in pyproject.toml")

          base = match.group(1)
          ref = os.environ["GITHUB_REF"]
          if ref.startswith("refs/tags/v"):
              version = ref.removeprefix("refs/tags/v")
          else:
              run_number = os.environ["GITHUB_RUN_NUMBER"]
              version = f"{base}.dev{run_number}"

          path.write_text(
              re.sub(r'^version = "[^"]+"$', f'version = "{version}"', text, count=1, flags=re.MULTILINE)
          )
          print(f"Stamped version: {version}")
          PY
      - run: uv sync --frozen --extra dev
      - run: uv run pytest -q
      - run: uv build
      - run: |
          python -m venv /tmp/uforia-terminal-release-venv
          source /tmp/uforia-terminal-release-venv/bin/activate
          pip install dist/*.whl
          uforia --help
          uforia-admin --help
  publish:
    if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
    needs: test-and-build
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write
    environment:
      name: pypi
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
      - name: Stamp package version
        shell: bash
        run: |
          python - <<'PY'
          import pathlib
          import re
          import os

          path = pathlib.Path("pyproject.toml")
          text = path.read_text()
          match = re.search(r'^version = "([^"]+)"$', text, re.MULTILINE)
          if not match:
              raise SystemExit("Could not find static version in pyproject.toml")

          base = match.group(1)
          ref = os.environ["GITHUB_REF"]
          if ref.startswith("refs/tags/v"):
              version = ref.removeprefix("refs/tags/v")
          else:
              run_number = os.environ["GITHUB_RUN_NUMBER"]
              version = f"{base}.dev{run_number}"

          path.write_text(
              re.sub(r'^version = "[^"]+"$', f'version = "{version}"', text, count=1, flags=re.MULTILINE)
          )
          print(f"Stamped version: {version}")
          PY
      - run: uv build
      - uses: pypa/gh-action-pypi-publish@release/v1
