#!/usr/bin/env bash
# Build a platform-specific .mcpb bundle for powerautomate-mcp.
#
# Native dependencies (better-sqlite3, keytar via @azure/msal-node-extensions)
# compile to platform-specific binaries, so a bundle is only valid for the OS +
# arch it was packed on. Run this on macOS to produce the macOS bundle and on
# Windows to produce the Windows bundle (the release CI does both).
#
# Output: dist-mcpb/powerautomate-mcp-<version>-<os>-<arch>.mcpb
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

VERSION="$(node -p "require('./package.json').version")"
OS="$(node -p "process.platform")"
ARCH="$(node -p "process.arch")"
STAGE="$ROOT/.mcpb-stage"
OUTDIR="$ROOT/dist-mcpb"
OUT="$OUTDIR/powerautomate-mcp-${VERSION}-${OS}-${ARCH}.mcpb"

echo "==> Building TypeScript"
npm run build

echo "==> Syncing manifest.json version to ${VERSION}"
node -e "const fs=require('fs');const m=JSON.parse(fs.readFileSync('manifest.json','utf8'));m.version=require('./package.json').version;fs.writeFileSync('manifest.json',JSON.stringify(m,null,2)+'\n');"
npx --yes @anthropic-ai/mcpb validate manifest.json

echo "==> Staging production dependencies in ${STAGE}"
rm -rf "$STAGE"
mkdir -p "$STAGE"
cp -R dist manifest.json package.json package-lock.json "$STAGE"/
[ -d templates ] && cp -R templates "$STAGE"/ || true
[ -f README.md ] && cp README.md "$STAGE"/ || true
[ -f LICENSE ] && cp LICENSE "$STAGE"/ || true

pushd "$STAGE" >/dev/null
# Prod-only install pulls the native prebuilds for THIS platform.
npm ci --omit=dev --no-audit --no-fund
popd >/dev/null

echo "==> Packing ${OUT}"
mkdir -p "$OUTDIR"
npx --yes @anthropic-ai/mcpb pack "$STAGE" "$OUT"

echo "==> Cleaning staging"
rm -rf "$STAGE"

echo ""
echo "Built: $OUT"
ls -lh "$OUT"
