#!/usr/bin/env python3
"""Apply AnyDesk migration"""

import psycopg2
import os
import sys

try:
    db_url = os.getenv('DATABASE_URL', 'postgresql://bmc_hub:bmc_hub@localhost:5433/bmc_hub')
    conn = psycopg2.connect(db_url)
    cursor = conn.cursor()
    
    with open('migrations/115_anydesk_sessions.sql', 'r') as f:
        sql = f.read()
    
    # Split by semicolons to execute statements separately
    statements = [s.strip() for s in sql.split(';') if s.strip()]
    
    for statement in statements:
        print(f"Executing: {statement[:80]}...")
        cursor.execute(statement)
    
    conn.commit()
    print("✅ Migration 115_anydesk_sessions.sql applied successfully!")
    
    # Verify tables created
    cursor.execute("""
        SELECT table_name FROM information_schema.tables 
        WHERE table_name LIKE 'anydesk%'
    """)
    
    tables = cursor.fetchall()
    print(f"✅ Created tables: {[t[0] for t in tables]}")
    
    cursor.close()
    conn.close()
    
except Exception as e:
    print(f"❌ Error: {str(e)}")
    import traceback
    traceback.print_exc()
    sys.exit(1)
