#!/bin/bash
# Apply Migration 020: Legal Templates — Typ-Renames + 11 neue Templates
set -e

CONTAINER="bp-compliance-backend"
MIGRATION_FILE="backend-compliance/migrations/020_legal_templates_new_types.sql"
REPO="/Users/benjaminadmin/Projekte/breakpilot-compliance"

echo "=== Migration 020: Legal Templates Typ-Renames + neue Templates ==="

# 1. Copy migration file to container
echo "[1/3] Kopiere Migration in Container..."
ssh macmini "/usr/local/bin/docker cp ${REPO}/${MIGRATION_FILE} ${CONTAINER}:/tmp/020_legal_templates_new_types.sql"

# 2. Execute migration
echo "[2/3] Fuehre Migration aus..."
ssh macmini "/usr/local/bin/docker exec ${CONTAINER} bash -c '
  python3 -c \"
import sys
sys.path.insert(0, \\\"/app\\\")
from classroom_engine.database import engine
with engine.connect() as conn:
    with open(\\\"/tmp/020_legal_templates_new_types.sql\\\") as f:
        sql = f.read()
    conn.execute(__import__(\\\"sqlalchemy\\\").text(sql))
    conn.commit()
    print(\\\"Migration 020 erfolgreich ausgefuehrt\\\")
\"
'"

# 3. Verify
echo "[3/3] Verifiziere..."
ssh macmini "/usr/local/bin/docker exec ${CONTAINER} bash -c '
  python3 -c \"
import sys
sys.path.insert(0, \\\"/app\\\")
from classroom_engine.database import engine
from sqlalchemy import text
with engine.connect() as conn:
    rows = conn.execute(text(\\\"SELECT document_type, COUNT(*) as cnt FROM compliance_legal_templates GROUP BY document_type ORDER BY document_type\\\")).fetchall()
    print(\\\"Typen in DB:\\\")
    for r in rows:
        print(f\\\"  {r[0]}: {r[1]} Template(s)\\\")
    total = conn.execute(text(\\\"SELECT COUNT(*) FROM compliance_legal_templates\\\")).scalar()
    print(f\\\"Gesamt: {total} Templates\\\")
\"
'"

echo "=== Migration 020 abgeschlossen ==="
