#!/bin/bash
set -euo pipefail
REMOTE="aissa@10.4.7.18"
PASS='Foodlinkk#2026'
SRC="/tmp/foodlinkk-deploy"
DEST="~/foodlinkk-command-center"

echo "=== Deploy platform upgrade ==="

sshpass -p "$PASS" rsync -avz --relative \
  "$SRC/./migrations/015_platform_upgrade.sql" \
  "$SRC/./cockpit/app/services/analytics_data.py" \
  "$SRC/./cockpit/app/routes/analytics.py" \
  "$SRC/./cockpit/app/routes/api.py" \
  "$SRC/./cockpit/app/routes/dashboard.py" \
  "$SRC/./cockpit/app/routes/retail.py" \
  "$SRC/./cockpit/app/services/briefing.py" \
  "$SRC/./cockpit/templates/analytics.html" \
  "$SRC/./cockpit/templates/dashboard.html" \
  "$SRC/./cockpit/templates/marketing.html" \
  "$SRC/./cockpit/templates/retail.html" \
  "$SRC/./cockpit/templates/base.html" \
  "$SRC/./cockpit/static/js/analytics.js" \
  "$SRC/./cockpit/static/js/briefing-charts.js" \
  "$SRC/./cockpit/static/js/live-pulse.js" \
  "$SRC/./cockpit/static/css/analytics.css" \
  "$SRC/./cockpit/static/css/pulse-theme.css" \
  "$SRC/./cockpit/static/css/herman-dashboard.css" \
  "$SRC/./tools-api/app/retail_360_routes.py" \
  "$SRC/./tools-api/app/briefing.py" \
  "$REMOTE:$DEST/"

sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$REMOTE" bash -s <<'REMOTE_SCRIPT'
set -e
cd ~/foodlinkk-command-center
echo "Running migration 015..."
docker compose exec -T postgres psql -U foodlinkk -d foodlinkk -f /migrations/015_platform_upgrade.sql 2>/dev/null || \
  cat migrations/015_platform_upgrade.sql | docker compose exec -T postgres psql -U foodlinkk -d foodlinkk

echo "Rebuilding containers..."
docker compose build tools-api cockpit
docker compose up -d tools-api cockpit
sleep 4
curl -sf http://localhost:8600/analytics/api/data?days=30 | head -c 200 && echo " ... analytics OK" || echo "WARN: analytics check"
curl -sf http://localhost:8600/api/herman/briefing/stats | head -c 200 && echo " ... briefing OK" || echo "WARN: briefing check"
echo "Deploy complete."
REMOTE_SCRIPT

echo "=== Done ==="
