#!/usr/bin/env python3
"""
Simple migration runner - applies anydesk_sessions schema
"""

import psycopg2
import sys

sql_statements = [
    """
    CREATE TABLE IF NOT EXISTS anydesk_sessions (
        id SERIAL PRIMARY KEY,
        anydesk_session_id VARCHAR(255) UNIQUE NOT NULL,
        contact_id INTEGER REFERENCES contacts(id) ON DELETE SET NULL,
        customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL,
        sag_id INTEGER REFERENCES sag_sager(id) ON DELETE SET NULL,
        session_link TEXT,
        device_info JSONB DEFAULT '{}',
        created_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
        started_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
        ended_at TIMESTAMP WITH TIME ZONE,
        duration_minutes INTEGER,
        status VARCHAR(50) NOT NULL DEFAULT 'draft',
        error_message TEXT,
        created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
        metadata JSONB DEFAULT '{}'
    )
    """,
    "CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_contact_id ON anydesk_sessions(contact_id)",
    "CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_customer_id ON anydesk_sessions(customer_id)",
    "CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_sag_id ON anydesk_sessions(sag_id)",
    "CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_created_by_user_id ON anydesk_sessions(created_by_user_id)",
    "CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_status ON anydesk_sessions(status)",
    "CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_started_at ON anydesk_sessions(started_at DESC)",
]

try:
    # Connect to database
    conn = psycopg2.connect("postgresql://bmc_hub:bmc_hub@localhost:5433/bmc_hub")
    cursor = conn.cursor()
    
    print("Applying AnyDesk migration...")
    for i, statement in enumerate(sql_statements, 1):
        preview = statement.replace('\n', ' ')[:80]
        print(f"  [{i}/{len(sql_statements)}] {preview}...")
        cursor.execute(statement)
    
    conn.commit()
    print("✅ All statements executed successfully")
    
    # Verify
    cursor.execute("SELECT COUNT(*) as count FROM information_schema.tables WHERE table_name = 'anydesk_sessions'")
    result = cursor.fetchone()
    if result[0] > 0:
        print("✅ anydesk_sessions table verified")
    
    cursor.close()
    conn.close()
    
except Exception as e:
    print(f"❌ Error: {e}", file=sys.stderr)
    sys.exit(1)
