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
from django.db.models import Q
from django.conf import settings
import inspect

def check_client_delete_function():
    """Check how the client_delete function interacts with notifications"""
    print("Checking client_delete function and its interactions...\n")
    
    # Import the function
    try:
        from users.views import client_delete
        print("Successfully imported client_delete function.")
        
        # Print the function source
        print("\nFunction source:")
        print(inspect.getsource(client_delete))
    except ImportError as e:
        print(f"Error importing client_delete function: {e}")
        return
    
    # Check for notification-related queries in the function
    print("\nAnalyzing function for notification-related queries...")
    source = inspect.getsource(client_delete)
    
    if "notification" in source.lower() or "notifications" in source.lower():
        print("Found direct references to notifications in the function.")
    else:
        print("No direct references to notifications found in the function.")
        print("The error might be coming from imported functions or signals.")
    
    # Check for related functions that might be called
    print("\nChecking for related functions that might be called...")
    related_functions = []
    
    # Common patterns for function calls
    function_patterns = [
        "delete(", 
        "save(", 
        "update(", 
        "filter(", 
        "exclude(", 
        "get(",
        "create("
    ]
    
    for line in source.split("\n"):
        for pattern in function_patterns:
            if pattern in line:
                related_functions.append(line.strip())
    
    if related_functions:
        print("Found potential related function calls:")
        for func in related_functions:
            print(f"  - {func}")
    else:
        print("No obvious related function calls found.")
    
    # Check for signal handlers that might be triggered on user delete
    print("\nChecking for signal handlers that might be triggered on user delete...")
    try:
        from django.db.models.signals import pre_delete, post_delete
        from users.models import CustomUser
        
        pre_delete_receivers = pre_delete._live_receivers(CustomUser)
        post_delete_receivers = post_delete._live_receivers(CustomUser)
        
        if pre_delete_receivers:
            print("Found pre_delete signal receivers for CustomUser:")
            for receiver in pre_delete_receivers:
                print(f"  - {receiver.__module__}.{receiver.__name__}")
        else:
            print("No pre_delete signal receivers found for CustomUser.")
        
        if post_delete_receivers:
            print("Found post_delete signal receivers for CustomUser:")
            for receiver in post_delete_receivers:
                print(f"  - {receiver.__module__}.{receiver.__name__}")
        else:
            print("No post_delete signal receivers found for CustomUser.")
    except Exception as e:
        print(f"Error checking signal handlers: {e}")
    
    # Try to trace SQL queries that would be executed
    print("\nAttempting to trace SQL queries that would be executed...")
    try:
        from django.db import connection
        from django.test.utils import CaptureQueriesContext
        from users.models import CustomUser
        
        # Get a test user (don't actually delete)
        test_user = CustomUser.objects.first()
        if test_user:
            print(f"Found test user: {test_user.username} (ID: {test_user.id})")
            print("Tracing queries that would be executed (without actually deleting)...")
            
            # Capture queries that would be executed in a delete operation
            with CaptureQueriesContext(connection) as ctx:
                # Simulate part of the delete process without actually deleting
                # This is just to see what queries might be generated
                related_objects = []
                for related in test_user._meta.get_fields():
                    if hasattr(related, 'related_model') and related.related_model:
                        try:
                            query = related.related_model.objects.filter(
                                **{related.field.name: test_user}
                            )
                            if query.exists():
                                related_objects.append((related.name, query.count()))
                        except Exception:
                            pass
            
            print(f"\nFound {len(ctx.captured_queries)} queries:")
            notification_queries = []
            for i, query in enumerate(ctx.captured_queries):
                if "notification" in query['sql'].lower():
                    notification_queries.append(query['sql'])
            
            if notification_queries:
                print(f"\nFound {len(notification_queries)} notification-related queries:")
                for i, query in enumerate(notification_queries):
                    print(f"\nQuery {i+1}:\n{query}")
            else:
                print("\nNo notification-related queries found in the simulation.")
                print("The error might occur in a different part of the deletion process.")
        else:
            print("No test users found in the database.")
    except Exception as e:
        print(f"Error tracing SQL queries: {e}")

if __name__ == "__main__":
    check_client_delete_function()