name: Publish to PyPI

on:
  release:
    types: [published]
  push:
    tags:
      - "v*"
  workflow_dispatch:
    inputs:
      tag:
        description: 'Tag to publish (e.g. v1.0.2.dev500). Overrides github.ref.'
        required: false
        type: string

permissions:
  contents: read
  id-token: write

jobs:
  publish:
    runs-on: ubuntu-latest
    environment: pypi
    steps:
      - name: Resolve target ref
        id: ref
        env:
          INPUT_TAG: ${{ inputs.tag }}
          DEFAULT_REF: ${{ github.ref_name }}
        run: |
          set -euo pipefail
          if [[ -n "$INPUT_TAG" ]]; then
            echo "ref=${INPUT_TAG}" >> "$GITHUB_OUTPUT"
          else
            echo "ref=${DEFAULT_REF}" >> "$GITHUB_OUTPUT"
          fi

      - uses: actions/checkout@v6
        with:
          ref: ${{ steps.ref.outputs.ref }}

      - name: Install uv
        uses: astral-sh/setup-uv@v8.0.0

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '22'
          cache: 'npm'
          cache-dependency-path: frontend/package-lock.json

      - name: Build frontend and bundle into package
        run: |
          set -euo pipefail
          cd frontend
          npm ci
          # Vite is configured (frontend/vite.config.ts) with
          # `outDir: '../src/openjarvis/server/static'` and
          # `emptyOutDir: true`, so the build writes directly into the
          # Python package's static dir and clears stale assets itself.
          # No rm/cp is needed — and the previous `dist/`-assuming logic
          # was broken because `frontend/dist/` is never produced.
          npm run build
          STATIC=../src/openjarvis/server/static
          test -s "$STATIC/index.html" || {
            echo "::error::${STATIC}/index.html missing or empty after build"
            exit 1
          }

      - name: Set version from tag
        env:
          REF: ${{ steps.ref.outputs.ref }}
        run: |
          set -euo pipefail
          # Strip leading "v" if present (e.g. v1.0.2.dev500 -> 1.0.2.dev500)
          VERSION="${REF#v}"
          if [[ -z "$VERSION" ]]; then
            echo "::error::Could not resolve version from ref '$REF'"
            exit 1
          fi
          sed -i "s/^version = \".*\"/version = \"${VERSION}\"/" pyproject.toml
          # Sanity check the substitution actually took
          grep -q "^version = \"${VERSION}\"" pyproject.toml || {
            echo "::error::sed failed to update pyproject.toml version"
            exit 1
          }
          echo "Building version $VERSION"

      - name: Build package
        run: uv build

      - name: Publish to PyPI
        run: uv publish
