#!/bin/bash
# Deploy webhook call ingest: clear stale per-BID secrets, restart FastAPI, smoke-test routes.
set -euo pipefail

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

echo "==> Clearing per-BID ingest_secret for enabled BIDs (shared INGEST_SECRET is used)..."
./venv/bin/python -c "
from fastapi_app import db_handler
db_handler.ensure_business_pipeline_config_table()
with db_handler.get_connection() as conn:
    cur = conn.cursor()
    cur.execute(\"UPDATE business_pipeline_config SET ingest_secret = '' WHERE webhook_ingest_enabled = 1\")
    conn.commit()
    print('cleared', cur.rowcount, 'row(s)')
"

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 4

echo "==> Route checks (401/403 = route exists; 404 = deploy failed)..."
for path in "/api/pipeline/6005/ingest/enable" "/api/pipeline/6005/ingest/disable"; do
  code=$(curl -s -o /dev/null -w "%{http_code}" -X POST "http://127.0.0.1:8012${path}" 2>/dev/null || echo "000")
  echo "  POST ${path} => HTTP ${code}"
done
code=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:8012/api/webhook/call-ingest/schema" 2>/dev/null || echo "000")
echo "  GET /api/webhook/call-ingest/schema => HTTP ${code}"

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

echo "==> Sync analytics workers (webhook BIDs: event-driven analytics after STT)..."
./venv/bin/python analytics_worker_supervisor.py --once || true

echo "==> Sync orchestrator supervisor (STT + analytics workers + enabled loops)..."
./venv/bin/python orchestrator_supervisor.py --once || true

echo "Done. Mcube URL: https://pca.syntheon.in/api/webhook/call-ingest"
echo "Set INGEST_SECRET in .env to the secret Mcube sends in X-Ingest-Secret."
echo "Restarting STT workers with fresh code..."
./venv/bin/python stt_worker_supervisor.py --once --restart || true
