import os
import sys
import django

# Set up Django environment
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection

def apply_notification_fix():
    """Apply the fix for the notification model issue"""
    print("Applying notification model fix...\n")
    
    # Check which tables exist
    with connection.cursor() as cursor:
        # Check notifications table
        cursor.execute("""
            SELECT COUNT(*) 
            FROM information_schema.tables 
            WHERE table_name='notifications';
        """)
        notifications_exists = cursor.fetchone()[0] > 0
        
        # Check utils_notification table
        cursor.execute("""
            SELECT COUNT(*) 
            FROM information_schema.tables 
            WHERE table_name='utils_notification';
        """)
        utils_notification_exists = cursor.fetchone()[0] > 0
    
    print(f"Table 'notifications' exists: {notifications_exists}")
    print(f"Table 'utils_notification' exists: {utils_notification_exists}\n")
    
    # Apply fix to notifications table
    if notifications_exists:
        with connection.cursor() as cursor:
            # Check if related_application_id column exists
            cursor.execute("""
                SELECT COUNT(*) 
                FROM information_schema.columns 
                WHERE table_name='notifications' 
                AND column_name='related_application_id';
            """)
            column_exists = cursor.fetchone()[0] > 0
            
            if not column_exists:
                print("Adding 'related_application_id' column to 'notifications' table...")
                cursor.execute("""
                    ALTER TABLE notifications 
                    ADD COLUMN related_application_id CHAR(32) NULL;
                """)
                print("Column added successfully.")
            else:
                print("Column 'related_application_id' already exists in 'notifications' table.")
    
    # Apply fix to utils_notification table
    if utils_notification_exists:
        with connection.cursor() as cursor:
            # Check if related_application_id column exists
            cursor.execute("""
                SELECT COUNT(*) 
                FROM information_schema.columns 
                WHERE table_name='utils_notification' 
                AND column_name='related_application_id';
            """)
            column_exists = cursor.fetchone()[0] > 0
            
            if not column_exists:
                print("Adding 'related_application_id' column to 'utils_notification' table...")
                cursor.execute("""
                    ALTER TABLE utils_notification 
                    ADD COLUMN related_application_id CHAR(32) NULL;
                """)
                print("Column added successfully.")
            else:
                print("Column 'related_application_id' already exists in 'utils_notification' table.")
    
    print("\nFix applied successfully. You should now be able to delete clients without errors.")
    print("\nNOTE: This is a temporary fix that adds the missing column to the database.")
    print("For a permanent solution, you should update the model definitions in your code.")
    print("See NOTIFICATION_MODEL_FIX_README.md for more details.")

if __name__ == "__main__":
    apply_notification_fix()