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, migrations, models
import django.db.models.deletion
from django.db.migrations.executor import MigrationExecutor
from django.apps import apps

def fix_notification_model():
    """
    Fix the missing related_application_id column in the notifications table
    """
    print("Starting notification model fix...")
    
    # Check if the column exists
    with connection.cursor() as cursor:
        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 column_exists:
        print("Column 'related_application_id' already exists in the notifications table.")
        return
    
    print("Column 'related_application_id' does not exist. Adding it now...")
    
    # Add the column to the database
    with connection.cursor() as cursor:
        cursor.execute("""
            ALTER TABLE notifications 
            ADD COLUMN related_application_id CHAR(32) NULL;
        """)
    
    print("Column 'related_application_id' added successfully.")
    
    # Create a foreign key constraint if needed
    try:
        with connection.cursor() as cursor:
            cursor.execute("""
                ALTER TABLE notifications 
                ADD CONSTRAINT notifications_related_application_id_fk 
                FOREIGN KEY (related_application_id) 
                REFERENCES loans_loanapplication(id);
            """)
        print("Foreign key constraint added successfully.")
    except Exception as e:
        print(f"Warning: Could not add foreign key constraint: {e}")
        print("This is not critical as Django will handle the relationship at the ORM level.")
    
    print("Notification model fix completed successfully.")

if __name__ == "__main__":
    fix_notification_model()