#!/bin/bash
# Apply Einwilligungen migration and rebuild backend-compliance on Mac Mini
# Usage: bash scripts/apply_einwilligungen_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 Einwilligungen migration (008_einwilligungen.sql)..."
ssh macmini "cd ${PROJECT_DIR} && \
  ${DOCKER} exec ${BACKEND_CONTAINER} \
    psql \"\${DATABASE_URL}\" -f /app/migrations/008_einwilligungen.sql \
    && echo 'Einwilligungen migration applied' \
    || echo 'psql failed, trying python...'"

ssh macmini "cd ${PROJECT_DIR} && \
  ${DOCKER} exec ${BACKEND_CONTAINER} \
    python3 -c \"
import psycopg2, os
conn = psycopg2.connect(os.environ['DATABASE_URL'])
conn.autocommit = True
cur = conn.cursor()
with open('/app/migrations/008_einwilligungen.sql', 'r') as f:
    sql = f.read()
cur.execute(sql)
cur.close()
conn.close()
print('Einwilligungen migration (python) applied')
\"" 2>/dev/null || echo "Note: Migration already applied or use manual SQL."

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 Einwilligungen endpoints..."
sleep 5
curl -sk "https://macmini:8002/api/compliance/einwilligungen/catalog" \
  -H "X-Tenant-ID: test-tenant" \
  | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'Einwilligungen catalog OK: {list(d.keys())}')" \
  || echo "Endpoint check needs backend restart"

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