#!/usr/bin/env bash
# build-sidecar.sh — bundle service into a single JS file and stage it for
# Tauri to pick up as an app resource.
#
# Usage:
#   bash scripts/build-sidecar.sh
#
# Output:
#   frontend/src-tauri/resources/service/index.js  (+ index.js.map)
#
# Why a JS bundle (not a native binary):
#   The Anthropic Agent SDK ships platform-specific native modules
#   (@anthropic-ai/claude-agent-sdk-{linux-x64,darwin-arm64,...}) that don't
#   compile cleanly through pkg/nexe/Bun-compile. Shipping a JS bundle + a
#   bundled node_modules tree, and invoking the system Node from Rust, is
#   the most reliable path. The runtime requirement is documented in
#   README — users must have Node 18+ on their machine.
set -euo pipefail

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

SERVICE="${ROOT}/service"
RES_DIR="${ROOT}/frontend/src-tauri/resources/service"

echo "[sidecar] building service bundle…"
(cd "${SERVICE}" && npm run build:bundle)

echo "[sidecar] staging into ${RES_DIR}"
rm -rf "${RES_DIR}"
mkdir -p "${RES_DIR}"
cp "${SERVICE}/dist-bundle/index.js" "${RES_DIR}/index.js"
[[ -f "${SERVICE}/dist-bundle/index.js.map" ]] && \
  cp "${SERVICE}/dist-bundle/index.js.map" "${RES_DIR}/index.js.map" || true

echo "[sidecar] done. Tauri will pick up resources/service/* on next bundle build."
