#!/bin/bash
# Apply VVT migration and rebuild backend-compliance on Mac Mini
# Usage: bash scripts/apply_vvt_migration.sh

set -e

DOCKER="/usr/local/bin/docker"
BACKEND_CONTAINER="bp-compliance-backend"
PROJECT_DIR="/Users/benjaminadmin/Projekte/breakpilot-compliance"

echo "==> Pushing code to Mac Mini..."
git push origin main

echo "==> Pulling code on Mac Mini..."
ssh macmini "cd ${PROJECT_DIR} && git pull --no-rebase origin main"

echo "==> Applying VVT migration (006_vvt.sql)..."
ssh macmini "cd ${PROJECT_DIR} && \
  ${DOCKER} exec ${BACKEND_CONTAINER} \
    python3 -c \"
import psycopg2
import os

conn = psycopg2.connect(os.environ['DATABASE_URL'])
conn.autocommit = True
cur = conn.cursor()
with open('/app/migrations/006_vvt.sql', 'r') as f:
    sql = f.read()
cur.execute(sql)
cur.close()
conn.close()
print('VVT migration applied successfully')
\"" || echo "Note: Migration may use different DB connection method. Trying psql..."

ssh macmini "cd ${PROJECT_DIR} && \
  ${DOCKER} exec ${BACKEND_CONTAINER} \
    psql \"\${DATABASE_URL}\" -f /app/migrations/006_vvt.sql \
    && echo 'VVT migration (psql) applied' \
    || echo 'Could not apply via psql, check manually'"

echo ""
echo "==> Rebuilding backend-compliance..."
ssh macmini "cd ${PROJECT_DIR} && \
  ${DOCKER} compose build --no-cache backend-compliance && \
  ${DOCKER} compose up -d backend-compliance"

echo ""
echo "==> Verifying VVT endpoint..."
sleep 5
curl -sf "https://macmini:8002/api/compliance/vvt/stats" \
  | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'VVT stats: total={d.get(\"total\",0)}')" \
  || echo "VVT endpoint check: needs backend restart"

echo ""
echo "Done. Check logs: ssh macmini '${DOCKER} logs -f ${BACKEND_CONTAINER}'"
