#!/usr/bin/env bash
# build-mcpb.sh — Produce a cross-platform .mcpb desktop-extension bundle.
#
# Stages only the runtime files plus a pure JS/WASM node_modules (optional deps
# omitted, so the native @resvg/resvg-js is excluded and the bundle works on any
# platform). PNG output is disabled in the bundle; SVG + interactive HTML remain.
#
# Usage:  bash scripts/build-mcpb.sh
# Output: dist/server-ena.mcpb

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
STAGE="$(mktemp -d)/server-ena"
OUT="${ROOT}/dist"

echo "Staging runtime files → ${STAGE}"
mkdir -p "${STAGE}" "${OUT}"

# Runtime files only (server.js resolves qeviz from node_modules, so the
# repo-root qeviz-*.js/html dev artifacts and tests are not needed).
cp "${ROOT}/server.js"     "${STAGE}/"
cp "${ROOT}/manifest.json" "${STAGE}/"
cp "${ROOT}/package.json"  "${STAGE}/"

# Keep the bundle's manifest version in lockstep with package.json.
VERSION="$(node -e "process.stdout.write(require('${ROOT}/package.json').version)")"
node -e "
  const fs = require('fs');
  const p = '${STAGE}/manifest.json';
  const m = JSON.parse(fs.readFileSync(p, 'utf8'));
  m.version = '${VERSION}';
  fs.writeFileSync(p, JSON.stringify(m, null, 2) + '\n');
"
echo "Manifest version synced to ${VERSION}"
cp "${ROOT}/package-lock.json" "${STAGE}/" 2>/dev/null || true
[ -f "${ROOT}/README.md" ] && cp "${ROOT}/README.md" "${STAGE}/"
[ -f "${ROOT}/.npmrc" ]    && cp "${ROOT}/.npmrc"    "${STAGE}/"

echo "Installing production deps without optional (pure JS/WASM)…"
( cd "${STAGE}" && npm install --omit=optional --omit=dev --no-audit --no-fund --silent )

# Drop the .npmrc so the registry token/config isn't shipped in the bundle.
rm -f "${STAGE}/.npmrc"

# Some npm versions (e.g. 9.x) still materialize root-level optionalDependencies
# despite --omit=optional. Remove the native rasterizer explicitly so the bundle
# stays pure JS/WASM and cross-platform. The server degrades gracefully without it.
rm -rf "${STAGE}"/node_modules/@resvg

# Sanity: the native rasterizer must NOT be present in the bundle.
if [ -d "${STAGE}/node_modules/@resvg" ]; then
    echo "ERROR: @resvg present in bundle — not cross-platform. Aborting." >&2
    exit 1
fi

echo "Packing bundle…"
mcpb pack "${STAGE}" "${OUT}/server-ena.mcpb"

echo ""
echo "Built: ${OUT}/server-ena.mcpb"
mcpb info "${OUT}/server-ena.mcpb" 2>/dev/null | head -20 || true
