#!/bin/bash
# Full build: OCaml WASM kernel + bundle + bytecode compile + deploy to shared/static/wasm/
#
# Usage: bash hosts/ocaml/browser/build-all.sh
#   Or via MCP: sx_build target="wasm"
set -e
cd "$(dirname "$0")"

echo "=== 1. Build WASM kernel ==="
# Remove assets dir that conflicts with dune's output target
rm -rf sx_browser.bc.wasm.assets
eval $(opam env 2>/dev/null)
cd ..
dune build browser/sx_browser.bc.wasm.js browser/sx_browser.bc.js bin/sx_server.exe 2>&1
cd browser

echo "=== 2. Bundle ==="
bash bundle.sh

echo "=== 3. Compile .sxbc bytecode ==="
node compile-modules.js dist

echo "=== 4. Deploy to shared/static/wasm/ ==="
DEST=../../../shared/static/wasm
cp dist/sx_browser.bc.wasm.js "$DEST/"
cp dist/sx_browser.bc.js "$DEST/"
rm -rf "$DEST/sx_browser.bc.wasm.assets"
cp -r dist/sx_browser.bc.wasm.assets "$DEST/"
cp dist/sx-platform.js "$DEST/sx-platform.js"
cp dist/sx/*.sx "$DEST/sx/"
cp dist/sx/*.sxbc "$DEST/sx/" 2>/dev/null || true
# Keep assets dir for Node.js WASM tests
cp -r dist/sx_browser.bc.wasm.assets ./ 2>/dev/null || true

echo "=== 5. Run WASM tests ==="
node test_wasm_native.js

echo "=== 6. Run bytecode regression tests ==="
node test_bytecode_repeat.js

echo "=== Done ==="
