name: Build Static WebUI

on:
  workflow_dispatch:
    inputs:
      version:
        description: "Version to build (e.g. 0.9.0)"
        required: true

permissions:
  contents: write

jobs:
  build:
    name: Build static frontend
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
        with: { version: 10 }
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm

      - run: pnpm install --frozen-lockfile
      - run: pnpm build:static

      - name: Zip static build
        run: |
          cd dist
          zip -r "../moku-webui-${{ github.event.inputs.version }}.zip" .

      - name: Upload WebUI artifact to release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          for i in $(seq 1 12); do
            RELEASE_ID=$(curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
              "https://api.github.com/repos/moku-project/Moku/releases" \
              | jq -r '.[] | select(.tag_name == "v${{ github.event.inputs.version }}") | .id' | head -1)
            [ -n "$RELEASE_ID" ] && break
            echo "Waiting for release... attempt $i"; sleep 15
          done
          [ -z "$RELEASE_ID" ] && { echo "ERROR: release not found"; exit 1; }

          curl -s -X POST \
            -H "Authorization: Bearer $GITHUB_TOKEN" \
            -H "Content-Type: application/zip" \
            --data-binary @"moku-webui-${{ github.event.inputs.version }}.zip" \
            "https://uploads.github.com/repos/moku-project/Moku/releases/$RELEASE_ID/assets?name=moku-webui-${{ github.event.inputs.version }}.zip"
