#!/usr/bin/env bash
set -e

if [ "$1" = "--debug" ]; then
    WASM_PACK_CONFIGURATION="--dev"
    NPM_PACKAGE_TARGET="package_debug"
else
    WASM_PACK_CONFIGURATION="--release"
    NPM_PACKAGE_TARGET="package"
fi

# Portable way to get repo root (works on macOS and Linux)
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"

# Build WASM package.
#
# `--no-default-features` skips the `shaders-all` default — slugs resolve via
# the live registry over the browser's `fetch` on web, so embedding the
# whole library (~86 KB of WGSL) into the wasm bundle is wasted size.
# Native Rust / Python / Swift / Kotlin builds keep the embedded library
# (no network needed by default).
wasm-pack build --target web $WASM_PACK_CONFIGURATION --out-dir "$SOURCE_DIR/platforms/web/pkg" -- --no-default-features

# Post-bindgen: patch generated glue with live-memory fallback for Uint8Array constructor
if command -v node >/dev/null 2>&1; then
  node "$SOURCE_DIR/platforms/web/patch_glue.mjs" "$SOURCE_DIR/platforms/web/pkg/fragmentcolor.js" || true
else
  echo "[build_web] node not found; skipping glue patch" >&2
fi

# Ensure npm package has a language-specific README
if [ -f "$SOURCE_DIR/README_JS.md" ]; then
  cp "$SOURCE_DIR/README_JS.md" "$SOURCE_DIR/platforms/web/pkg/README.md"
fi

# Distribute the pkg to web subprojects so local dev servers can import from ./pkg
for SUB in "repl" "healthcheck"; do
  DEST="$SOURCE_DIR/platforms/web/$SUB/pkg"
  mkdir -p "$DEST"
  # Copy the entire pkg directory contents (JS, WASM, .d.ts, and any helpers)
  rsync -a --delete "$SOURCE_DIR/platforms/web/pkg/" "$DEST/" 2>/dev/null || cp -a "$SOURCE_DIR/platforms/web/pkg/." "$DEST/"
done
