#!/bin/bash
# Apply Training Engine migrations on Mac Mini and verify
# Usage: bash scripts/apply_training_migrations.sh

set -e

DOCKER="/usr/local/bin/docker"
CONTAINER="bp-compliance-ai-sdk"
PROJECT_DIR="/Users/benjaminadmin/Projekte/breakpilot-compliance"

echo "==> Applying Training Engine migrations on Mac Mini..."

ssh macmini "cd ${PROJECT_DIR} && \
  ${DOCKER} exec ${CONTAINER} \
    psql \"\${DATABASE_URL}\" -f /migrations/014_training_engine.sql \
    && echo 'Migration 014 applied' \
    || echo 'Migration 014 may already be applied (table exists)'"

ssh macmini "cd ${PROJECT_DIR} && \
  ${DOCKER} exec ${CONTAINER} \
    psql \"\${DATABASE_URL}\" -f /migrations/016_training_media.sql \
    && echo 'Migration 016 applied' \
    || echo 'Migration 016 may already be applied'"

echo ""
echo "==> Verifying training service..."
curl -sf "https://macmini:8093/health" && echo "Health check: OK" || echo "Health check: FAILED"

echo ""
echo "==> Checking training modules endpoint..."
curl -sf \
  "https://macmini:8093/sdk/v1/training/modules" \
  -H "X-Tenant-ID: 9282a473-5c95-4b3a-bf78-0ecc0ec71d3e" \
  | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'Modules found: {len(d.get(\"modules\",[]))}')" \
  || echo "Training modules endpoint check failed"

echo ""
echo "Done."
