#!/bin/bash
# Deploy call summary config feature: DB columns + restart API.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

echo "==> Ensuring DB columns and saving test config for BID 6004 (optional)..."
./venv/bin/python scripts/ensure_summary_config_setup.py --bid "${BID:-6004}" --mode "${MODE:-discovery_recap}"

echo "==> Restarting FastAPI (gunicorn on :8012)..."
pkill -f "gunicorn -c .*gunicorn_fastapi_conf" 2>/dev/null || true
sleep 2
nohup ./venv/bin/python -m gunicorn -c gunicorn_fastapi_conf.py fastapi_app:app >> fastapi_restart.log 2>&1 &
sleep 3

CODE=$(curl -s -o /dev/null -w "%{http_code}" -X PUT "http://127.0.0.1:8012/pipeline/6004/summary-config" \
  -H "Content-Type: application/json" -d '{"summary_mode":"discovery_recap"}')
echo "PUT /pipeline/6004/summary-config (no auth) => HTTP $CODE"
echo "  (401 = route exists; 404 = restart failed / old code)"

FRONT="$(cd "$ROOT/../dashboard-frontend" && pwd)"
if [ -d "$FRONT" ]; then
  echo "==> Building frontend..."
  (cd "$FRONT" && npm run build)
  echo "Deploy frontend dist/ to your web root (e.g. nginx for pca.syntheon.in), then hard-refresh browser."
fi

echo "Done."
