#!/bin/sh
set -eu

echo "Building admin web artifacts..."
cd /opt/bytelyst/learning_ai_common_plat && pnpm -r --filter @bytelyst/admin-web... build
pnpm --filter @bytelyst/admin-web deploy --legacy --ignore-scripts /tmp/admin-deploy

echo "Copying frontend assets into admin-web..."
docker cp /tmp/admin-deploy/.next/standalone admin-web:/app/
docker cp /tmp/admin-deploy/.next/static admin-web:/app/.next/static
docker cp /tmp/admin-deploy/public admin-web:/app/public

echo "Restarting admin-web..."
docker restart admin-web >/dev/null

echo "Waiting for web readiness..."
for _ in 1 2 3 4 5 6 7 8 9 10; do
  if curl -s http://127.0.0.1:3001 > /dev/null; then
    break
  fi
  sleep 2
done

echo "Admin Web hotcopy deployment complete"
echo "Web status:"
curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:3001

# Cleanup
rm -rf /tmp/admin-deploy