#!/usr/bin/env bash
# Deploy latest QA Playwright worker and restart PM2.
# Run on the worker host as root or apisaicountly:
#   bash scripts/deploy-and-restart.sh

set -euo pipefail

ROOT="${QA_WORKER_ROOT:-/home/apisaicountly/public_html/worker.apis.aicountly.com}"
cd "$ROOT"

echo "==> Worker dir: $ROOT"

if [ -d .git ]; then
  echo "==> git pull"
  git fetch --all --prune
  git pull --ff-only || git reset --hard origin/main
else
  echo "ERROR: $ROOT is not a git checkout."
  echo "Clone apis-aicountly and point this path at worker.apis.aicountly.com, or copy updated files."
  exit 1
fi

echo "==> npm install (production deps)"
npm install --omit=dev

echo "==> Restart PM2 qa-worker"
if pm2 describe qa-worker >/dev/null 2>&1; then
  pm2 restart qa-worker --update-env
else
  pm2 start npm --name qa-worker -- start
  pm2 save
fi

pm2 status qa-worker
echo "==> Recent logs (Ctrl+C to stop)"
pm2 logs qa-worker --lines 40
