#!/usr/bin/env bash
# ============================================================
# HalaVoice — module bootstrap (fresh server / after code restore)
#
# Installs dependencies and builds everything the app needs to run.
# Idempotent: safe to re-run. Does NOT touch the database.
#
# Steps:
#   1. npm install (root app)
#   2. compile plugins  (scripts/build-plugin-backend.js)
#   3. build frontend + server bundle (npm run build)
#   4. npm install for the WhatsApp service (whatsapp-server-v2)
#   5. sanity check that dist/index.js exists
#
# Usage: ops/setup-modules.sh
# ============================================================
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
cd "$REPO_ROOT"
need node; need npm

log "1/5 Installing root dependencies…"
npm install --no-audit --no-fund

log "2/5 Compiling plugins…"
if [ -f scripts/build-plugin-backend.js ]; then
  node scripts/build-plugin-backend.js
else
  warn "scripts/build-plugin-backend.js not found — skipping plugin compile"
fi

log "3/5 Building frontend + server…"
npm run build

log "4/5 Installing WhatsApp service dependencies…"
if [ -d whatsapp-server-v2 ]; then
  ( cd whatsapp-server-v2 && npm install --no-audit --no-fund )
else
  warn "whatsapp-server-v2 not present — skipping"
fi

log "5/5 Verifying build…"
[ -f dist/index.js ] || die "dist/index.js missing — build failed"
ok "Modules ready. Start with: pm2 start ecosystem.config.cjs (or pm2 restart agentlabs)"
