#!/usr/bin/env python3
"""
Test the exact operation that's causing the error
"""

import os
import sys
import django
import logging
from django.db import connection, transaction

# Setup Django for production
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def test_exact_operation():
    """Test the exact operation that's failing"""
    logger.info("Testing the exact operation that's failing...")
    
    try:
        from django.contrib.auth.models import Permission
        from users.models import CustomUser
        
        # Get a user and permission
        user = CustomUser.objects.first()
        permission = Permission.objects.first()
        
        if not user:
            logger.error("No user found")
            return False
        
        if not permission:
            logger.error("No permission found")
            return False
        
        logger.info(f"User: {user.username} (ID: {user.id})")
        logger.info(f"Permission: {permission.name} (ID: {permission.id})")
        
        # Test the exact operation that was failing
        logger.info("Testing user.user_permissions.add(permission)...")
        
        try:
            user.user_permissions.add(permission)
            logger.info("✅ SUCCESS: Permission added successfully")
            
            # Check if it was actually added
            user_permissions = user.user_permissions.all()
            logger.info(f"User now has {user_permissions.count()} permissions")
            
            # Remove it
            user.user_permissions.remove(permission)
            logger.info("✅ SUCCESS: Permission removed successfully")
            
            return True
            
        except Exception as e:
            logger.error(f"❌ FAILED: {e}")
            import traceback
            traceback.print_exc()
            return False
        
    except Exception as e:
        logger.error(f"❌ Error in test: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_with_different_users():
    """Test with different users to see if it's user-specific"""
    logger.info("Testing with different users...")
    
    try:
        from django.contrib.auth.models import Permission
        from users.models import CustomUser
        
        users = CustomUser.objects.all()[:3]
        permission = Permission.objects.first()
        
        if not users.exists() or not permission:
            logger.error("No users or permission found")
            return False
        
        for user in users:
            logger.info(f"Testing with user: {user.username} (ID: {user.id})")
            
            try:
                user.user_permissions.add(permission)
                logger.info(f"✅ SUCCESS with {user.username}")
                user.user_permissions.remove(permission)
            except Exception as e:
                logger.error(f"❌ FAILED with {user.username}: {e}")
                return False
        
        return True
        
    except Exception as e:
        logger.error(f"❌ Error in test: {e}")
        return False

def test_with_different_permissions():
    """Test with different permissions to see if it's permission-specific"""
    logger.info("Testing with different permissions...")
    
    try:
        from django.contrib.auth.models import Permission
        from users.models import CustomUser
        
        user = CustomUser.objects.first()
        permissions = Permission.objects.all()[:3]
        
        if not user or not permissions.exists():
            logger.error("No user or permissions found")
            return False
        
        for permission in permissions:
            logger.info(f"Testing with permission: {permission.name} (ID: {permission.id})")
            
            try:
                user.user_permissions.add(permission)
                logger.info(f"✅ SUCCESS with {permission.name}")
                user.user_permissions.remove(permission)
            except Exception as e:
                logger.error(f"❌ FAILED with {permission.name}: {e}")
                return False
        
        return True
        
    except Exception as e:
        logger.error(f"❌ Error in test: {e}")
        return False

def main():
    """Main function"""
    logger.info("=" * 60)
    logger.info("TESTING EXACT ERROR SCENARIO")
    logger.info("=" * 60)
    
    tests = [
        ("Exact Operation Test", test_exact_operation),
        ("Different Users Test", test_with_different_users),
        ("Different Permissions Test", test_with_different_permissions),
    ]
    
    all_passed = True
    
    for test_name, test_func in tests:
        logger.info(f"\n--- Running {test_name} ---")
        try:
            result = test_func()
            if result:
                logger.info(f"✅ {test_name} PASSED")
            else:
                logger.error(f"❌ {test_name} FAILED")
                all_passed = False
        except Exception as e:
            logger.error(f"❌ {test_name} ERROR: {e}")
            all_passed = False
    
    logger.info("\n" + "=" * 60)
    if all_passed:
        logger.info("🎉 ALL TESTS PASSED! The permission system is working correctly.")
        logger.info("If you're still getting the error, it might be coming from a different part of your application.")
    else:
        logger.error("❌ SOME TESTS FAILED. Check the logs above for details.")
    
    return all_passed

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
