#!/usr/bin/env python3
"""
Run migration to add contact columns to restaurants table
"""

from sqlalchemy import create_engine, text
from urllib.parse import quote_plus
import os

def run_migration():
    print("🚀 Starting migration to add contact columns to restaurants table...")
    
    DATABASE_URL = f"postgresql://postgres:{quote_plus('F@f@k0s!!')}@localhost:5432/bookbeach"
    engine = create_engine(DATABASE_URL)
    
    # Read the SQL migration file
    migration_file = "add_restaurant_contact_columns.sql"
    
    if not os.path.exists(migration_file):
        print(f"❌ Migration file {migration_file} not found!")
        return False
    
    with open(migration_file, 'r', encoding='utf-8') as f:
        migration_sql = f.read()
    
    try:
        with engine.connect() as db:
            # Split and execute SQL statements
            statements = [stmt.strip() for stmt in migration_sql.split(';') if stmt.strip()]
            
            for i, stmt in enumerate(statements):
                if stmt.strip():
                    print(f"📝 Executing statement {i+1}/{len(statements)}...")
                    if stmt.strip().upper().startswith('SELECT'):
                        # For SELECT statements, print results
                        result = db.execute(text(stmt)).fetchall()
                        if result:
                            print("✅ Verification results:")
                            for row in result:
                                print(f"  {row}")
                    else:
                        db.execute(text(stmt))
                        print(f"✅ Statement {i+1} executed successfully")
            
            db.commit()
            print("🎉 Migration completed successfully!")
            
            # Final verification
            print("\n📋 Final verification - checking new columns:")
            result = db.execute(text("""
                SELECT column_name, data_type, is_nullable
                FROM information_schema.columns 
                WHERE table_name = 'restaurants' 
                  AND column_name IN ('phone', 'email', 'website', 'updated_at')
                ORDER BY column_name
            """)).fetchall()
            
            for col_name, data_type, is_nullable in result:
                print(f"  ✅ {col_name}: {data_type} (nullable: {is_nullable})")
            
            return True
            
    except Exception as e:
        print(f"❌ Migration failed: {str(e)}")
        return False

if __name__ == '__main__':
    success = run_migration()
    if success:
        print("\n🎯 Next steps:")
        print("1. Backend code will be updated to include new fields")
        print("2. Admin forms will be updated to include new input fields")
        print("3. API endpoints will be updated to handle new fields")
    else:
        print("\n💥 Migration failed. Please check the error above.")