#!/usr/bin/env python3
"""
Test script to verify setup.py fixes work correctly
Run this after setup.py to test the fixes
"""

import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
django.setup()

def test_user_model():
    """Test user model and admin user"""
    print("Testing user model...")
    try:
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        # Test admin user exists
        admin_user = User.objects.get(email='admin@branchbusinessadvance.com')
        print(f"✅ Admin user exists: {admin_user.email}")
        print(f"   Role: {admin_user.role}")
        print(f"   Is staff: {admin_user.is_staff}")
        print(f"   Is superuser: {admin_user.is_superuser}")
        
        return True
    except Exception as e:
        print(f"❌ User model test failed: {e}")
        return False

def test_role_permissions():
    """Test role permissions system"""
    print("\nTesting role permissions...")
    try:
        from users.models import RolePermission
        from django.db import connection
        
        # Get actual roles from database
        with connection.cursor() as cursor:
            cursor.execute('SELECT DISTINCT role FROM role_permissions ORDER BY role')
            actual_roles = [row[0] for row in cursor.fetchall()]
        
        total_permissions = 0
        expected_roles = ['admin', 'team_leader', 'loan_officer', 'secretary', 'auditor', 'borrower']
        
        print("   Role permissions breakdown:")
        for role in expected_roles:
            count = RolePermission.objects.filter(role=role).count()
            print(f"   {role.replace('_', ' ').title()}: {count} permissions")
            total_permissions += count
        
        print(f"✅ Total permissions: {total_permissions}")
        
        # Verify we have the expected minimum permissions
        if total_permissions >= 160:  # We expect around 160 permissions
            print("✅ Role permissions system is working correctly")
            return True
        else:
            print(f"❌ Expected at least 160 permissions, found {total_permissions}")
            return False
        
    except Exception as e:
        print(f"❌ Role permissions test failed: {e}")
        return False

def test_database_tables():
    """Test critical database tables exist"""
    print("\nTesting database tables...")
    try:
        from django.db import connection
        
        critical_tables = [
            'users',
            'role_permissions', 
            'user_permissions',
            'auth_permission',
            'django_content_type',
            'users_customuser_user_permissions',
            'users_customuser_groups'
        ]
        
        with connection.cursor() as cursor:
            for table in critical_tables:
                cursor.execute(f"""
                    SELECT COUNT(*) 
                    FROM INFORMATION_SCHEMA.TABLES 
                    WHERE TABLE_SCHEMA = DATABASE() 
                    AND TABLE_NAME = '{table}'
                """)
                
                if cursor.fetchone()[0] > 0:
                    print(f"   ✅ {table} table exists")
                else:
                    print(f"   ❌ {table} table missing")
                    return False
        
        return True
        
    except Exception as e:
        print(f"❌ Database tables test failed: {e}")
        return False

def test_collation_fix():
    """Test database collation is consistent"""
    print("\nTesting database collation...")
    try:
        from django.db import connection
        
        with connection.cursor() as cursor:
            # Test a simple query that would fail with collation issues
            cursor.execute("""
                SELECT COUNT(*) FROM users 
                WHERE role = 'admin' 
                AND status = 'active'
            """)
            
            result = cursor.fetchone()[0]
            print(f"✅ Collation test query successful: {result} admin users found")
            return True
            
    except Exception as e:
        print(f"❌ Collation test failed: {e}")
        return False

def test_user_deletion_safety():
    """Test user deletion functions exist"""
    print("\nTesting user deletion safety...")
    try:
        # Check if safe deletion function exists in users/views.py
        views_file = 'users/views.py'
        if os.path.exists(views_file):
            with open(views_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            if 'def safe_delete_user_records(' in content:
                print("✅ Safe user deletion function exists")
                return True
            else:
                print("❌ Safe user deletion function missing")
                return False
        else:
            print("❌ users/views.py file not found")
            return False
            
    except Exception as e:
        print(f"❌ User deletion safety test failed: {e}")
        return False

def main():
    """Run all tests"""
    print("🧪 Running setup fixes verification tests...\n")
    
    tests = [
        test_user_model,
        test_role_permissions,
        test_database_tables,
        test_collation_fix,
        test_user_deletion_safety
    ]
    
    passed = 0
    total = len(tests)
    
    for test in tests:
        if test():
            passed += 1
    
    print(f"\n📊 Test Results: {passed}/{total} tests passed")
    
    if passed == total:
        print("🎉 All tests passed! Setup fixes are working correctly.")
        return True
    else:
        print("⚠️  Some tests failed. Please check the issues above.")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)