#!/bin/bash
set -e
PASS='Foodlinkk#2026'
VM18=aissa@10.4.7.18
VM19=aissa@10.4.7.19
DEP=/tmp/foodlinkk-deploy

ssh $VM18 "mkdir -p /tmp/fk-deploy"

echo "=== Copy files to VM 106 ==="
sshpass -p "$PASS" scp -o StrictHostKeyChecking=no \
  "$DEP/migrations/009_full_upgrade.sql" \
  "$DEP/tools-api/app/retail.py" \
  "$DEP/tools-api/app/research.py" \
  "$DEP/tools-api/app/recommendations.py" \
  "$DEP/tools-api/app/logging_middleware.py" \
  "$DEP/tools-api/patch_main.py" \
  "$DEP/cockpit/app/routes/retail.py" \
  "$DEP/cockpit/app/routes/reco_proxy.py" \
  "$DEP/cockpit/templates/retail.html" \
  "$DEP/cockpit/static/retail.css" \
  "$DEP/cockpit/patch_cockpit.py" \
  "$DEP/cockpit/patch_admin.py" \
  $VM18:/tmp/fk-deploy/

echo "=== Install on VM 106 ==="
sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no $VM18 'bash -s' << 'REMOTE'
set -e
cp /tmp/fk-deploy/retail.py ~/foodlinkk-command-center/tools-api/app/
cp /tmp/fk-deploy/research.py ~/foodlinkk-command-center/tools-api/app/
cp /tmp/fk-deploy/recommendations.py ~/foodlinkk-command-center/tools-api/app/
cp /tmp/fk-deploy/logging_middleware.py ~/foodlinkk-command-center/tools-api/app/
cp /tmp/fk-deploy/retail.py ~/foodlinkk-command-center/cockpit/app/routes/
cp /tmp/fk-deploy/reco_proxy.py ~/foodlinkk-command-center/cockpit/app/routes/
cp /tmp/fk-deploy/retail.html ~/foodlinkk-command-center/cockpit/templates/
cp /tmp/fk-deploy/retail.css ~/foodlinkk-command-center/cockpit/static/
python3 /tmp/fk-deploy/patch_main.py
python3 /tmp/fk-deploy/patch_cockpit.py
python3 /tmp/fk-deploy/patch_admin.py
docker exec -i foodlinkk_db psql -U aissa -d foodlinkk < /tmp/fk-deploy/009_full_upgrade.sql
cd ~/foodlinkk-command-center
docker compose build tools-api cockpit
docker compose up -d tools-api cockpit
REMOTE

echo "=== VM 105 cron ==="
sshpass -p "$PASS" scp -o StrictHostKeyChecking=no \
  "$DEP/scripts/research_refresh.py" $VM19:/home/aissa/foodlinkk-ai/scripts/
sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no $VM19 \
  'chmod +x ~/foodlinkk-ai/scripts/research_refresh.py; (crontab -l 2>/dev/null | grep -v research_refresh; echo "0 6 * * * /usr/bin/python3 /home/aissa/foodlinkk-ai/scripts/research_refresh.py >> /tmp/foodlinkk-research.log 2>&1") | crontab -'

echo "=== Initial research cycle ==="
sleep 20
curl -sf -X POST http://10.4.7.18:8700/research/run && echo
curl -sf -X POST http://10.4.7.18:8700/recommendations/generate && echo
curl -sf http://10.4.7.18:8700/retail/stats && echo
curl -sf -o /dev/null -w "cockpit_retail:%{http_code}\n" http://10.4.7.18:8600/retail
echo DONE
