#!/usr/bin/env python3
"""
Apply Lead Management Tables Migration
"""
import psycopg2
import os
from db import get_db_connection

def apply_migration():
    """Apply the lead tables migration"""
    try:
        # Read migration SQL
        migration_file = os.path.join(os.path.dirname(__file__), 
                                     'migrations', 'create_lead_tables.sql')
        
        with open(migration_file, 'r') as f:
            migration_sql = f.read()
        
        # Connect and execute
        with get_db_connection() as conn:
            cur = conn.cursor()
            
            print("Applying lead management tables migration...")
            cur.execute(migration_sql)
        
            # Verify tables were created
            cur.execute("""
                SELECT table_name 
                FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name LIKE 'lead_%'
                ORDER BY table_name
            """)
            
            tables = cur.fetchall()
            print(f"\nCreated {len(tables)} tables:")
            for table in tables:
                print(f"  - {table[0]}")
            
            cur.close()
        
        print("\n✅ Migration completed successfully!")
        
    except FileNotFoundError:
        print(f"❌ Migration file not found: {migration_file}")
    except psycopg2.Error as e:
        print(f"❌ Database error: {e}")
    except Exception as e:
        print(f"❌ Unexpected error: {e}")

if __name__ == "__main__":
    apply_migration()