#!/bin/bash
# Apply all template migrations (087-105) to the compliance database
# Run this on the Mac Mini after pulling the branch

set -e

CONTAINER="bp-compliance-backend"
MIGRATIONS_DIR="/app/migrations"

echo "=== Applying Template Migrations 087-105 ==="

for f in 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105; do
    FILE=$(ls ${MIGRATIONS_DIR}/${f}_*.sql 2>/dev/null | head -1)
    if [ -n "$FILE" ]; then
        echo "→ Applying $(basename $FILE)..."
        python3 -c "
import os, sys
sys.path.insert(0, '/app')
from compliance.db.database import get_db_url
import psycopg2

url = get_db_url()
conn = psycopg2.connect(url)
conn.autocommit = True
cur = conn.cursor()
with open('$FILE', 'r') as f:
    sql = f.read()
try:
    cur.execute(sql)
    print(f'  ✓ Applied successfully')
except Exception as e:
    print(f'  ⚠ Warning: {e}')
cur.close()
conn.close()
" 2>&1 || echo "  ⚠ Skipped (may already be applied)"
    fi
done

echo ""
echo "=== Migration complete ==="
echo "Verify: SELECT count(*) FROM compliance_legal_templates;"
