#!/bin/sh
set -eu

echo "Building web and backend artifacts..."
pnpm --filter @bytelyst/trading-web build
pnpm --filter @bytelyst/trading-backend build

echo "Copying frontend assets into invttrdg-web..."
docker cp web/dist/. invttrdg-web:/usr/share/nginx/html

echo "Copying backend apiServer bundle into invttrdg-backend..."
docker cp backend/dist/backend/src/services/apiServer.js invttrdg-backend:/app/backend/dist/backend/src/services/apiServer.js

echo "Restarting invttrdg-backend..."
docker restart invttrdg-backend >/dev/null

echo "Waiting for backend readiness..."
for _ in 1 2 3 4 5 6 7 8 9 10; do
  READY_JSON="$(curl -s http://127.0.0.1:4025/health/ready || true)"
  echo "$READY_JSON" | grep -q '"status":"healthy"' && break
  sleep 2
done

echo "Public asset summary:"
curl -s https://invttrdg.bytelyst.com | grep -o 'index-[^"[:space:]]*\.js\|index-[^"[:space:]]*\.css' | head

echo "Backend readiness:"
curl -s http://127.0.0.1:4025/health/ready
