name: Web WASM Rebuild

# CI is the single source of truth for solitaire_server/web/pkg/.
#
# The wasm artifacts cannot be reproduced byte-for-byte on an arbitrary
# contributor machine: even with identical rustc 1.95.0 / LLVM 22.1.2, the same
# flags, the same Cargo.lock and remapped source paths, the output still differs
# by host environment. So rather than police freshness with a rebuild-and-diff
# gate (which false-failed for exactly that reason), CI rebuilds the artifacts
# itself on every master change to a wasm-feeding crate and commits them back.
#
# Result: the deployed pkg/ can't silently rot, and contributors never need to
# run build_wasm.sh by hand. The commit touches only pkg/, which is not in this
# workflow's trigger paths (so it does not re-trigger here) but does match
# docker-build's, so the refreshed wasm deploys.

on:
  push:
    branches: [master]
    paths:
      - 'solitaire_core/**'
      - 'solitaire_engine/**'
      - 'solitaire_data/**'
      - 'solitaire_sync/**'
      - 'solitaire_wasm/**'
      - 'solitaire_web/**'
      - 'Cargo.toml'
      - 'Cargo.lock'
      - 'build_wasm.sh'
      - '.gitea/workflows/web-wasm-rebuild.yml'
  workflow_dispatch:

concurrency:
  group: web-wasm-rebuild
  cancel-in-progress: false

jobs:
  rebuild:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.CI_TOKEN }}

      - name: Install Rust 1.95.0
        uses: dtolnay/rust-toolchain@master
        with:
          toolchain: 1.95.0
          targets: wasm32-unknown-unknown

      - name: Cache cargo build
        uses: Swatinem/rust-cache@v2

      - name: Install wasm-bindgen-cli + wasm-pack (pinned)
        uses: taiki-e/install-action@v2
        with:
          tool: wasm-bindgen-cli@0.2.120,wasm-pack@0.14.0

      - name: Install binaryen 130 (wasm-opt, pinned)
        run: |
          set -euo pipefail
          curl -sSL \
            https://github.com/WebAssembly/binaryen/releases/download/version_130/binaryen-version_130-x86_64-linux.tar.gz \
            | tar xz
          echo "$PWD/binaryen-version_130/bin" >> "$GITHUB_PATH"

      - name: Rebuild WASM artifacts
        run: ./build_wasm.sh

      - name: Commit refreshed artifacts if changed
        run: |
          set -euo pipefail
          if git diff --quiet -- solitaire_server/web/pkg/; then
            echo "pkg/ already up to date — nothing to commit."
            exit 0
          fi
          git config user.email "ci@gitea.local"
          git config user.name "Gitea CI"
          git add solitaire_server/web/pkg/
          git commit -m "chore(web): regenerate wasm artifacts"
          # master is unprotected; retry once if the tip moved under us.
          git push origin HEAD:master || {
            git fetch origin master
            git rebase origin/master
            git push origin HEAD:master
          }
