#!/usr/bin/env python3
"""
Test script for simplified permissions system
"""

import os
import sys
import django

# Add the project directory to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

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

from users.models import CustomUser
from users.simplified_permissions_views import SIMPLIFIED_PERMISSIONS

def test_simplified_permissions():
    print("🧪 Testing simplified permissions system...")
    
    # Test 1: Check if SIMPLIFIED_PERMISSIONS is properly defined
    print(f"✅ SIMPLIFIED_PERMISSIONS has {len(SIMPLIFIED_PERMISSIONS)} modules")
    
    # Test 2: Check if we have users to test with
    users = CustomUser.objects.filter(role__in=['admin', 'team_leader', 'loan_officer']).exclude(role='borrower')
    print(f"✅ Found {users.count()} staff users for testing")
    
    if users.exists():
        test_user = users.first()
        print(f"✅ Test user: {test_user.get_full_name()} ({test_user.role})")
        
        # Test 3: Check if user has permissions
        permissions = test_user.get_effective_permissions()
        print(f"✅ User has {len(permissions)} permission modules")
        
        # Test 4: Check specific permissions
        dashboard_perms = permissions.get('dashboard', {})
        print(f"✅ Dashboard permissions: {len(dashboard_perms)} actions")
        
        # Test 5: Test URL generation
        from django.urls import reverse
        try:
            url = reverse('users:simplified_user_permissions', kwargs={'user_id': test_user.id})
            print(f"✅ URL generated: {url}")
        except Exception as e:
            print(f"❌ URL generation failed: {e}")
            return False
        
        print("\n🎯 Test Results:")
        print(f"   - Modules: {list(SIMPLIFIED_PERMISSIONS.keys())}")
        print(f"   - Actions per module: {len(list(SIMPLIFIED_PERMISSIONS.values())[0])}")
        print(f"   - Test URL: {url}")
        
        return True
    else:
        print("❌ No staff users found for testing")
        return False

if __name__ == '__main__':
    success = test_simplified_permissions()
    if success:
        print("\n✅ All tests passed! The simplified permissions system is ready to use.")
        print("\n📋 Next steps:")
        print("1. Go to http://127.0.0.1:8000/users/admins/")
        print("2. Click the purple shield icon next to any user")
        print("3. Use the simplified permissions interface")
    else:
        print("\n❌ Some tests failed. Please check the setup.")
        sys.exit(1)