#!/usr/bin/env python
"""
Test script to verify granular permissions functionality
"""
import os
import sys
import django

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

from django.core.management import call_command
from users.enhanced_permissions_models import PagePermission, RolePermissionTemplate
from users.models import CustomUser


def test_permission_seeding():
    """Test that permissions are properly seeded"""
    print("Testing permission seeding...")
    
    # Clear existing data
    PagePermission.objects.all().delete()
    RolePermissionTemplate.objects.all().delete()
    
    # Seed permissions
    call_command('seed_page_permissions')
    call_command('seed_role_templates')
    
    # Verify seeding
    total_permissions = PagePermission.objects.count()
    total_templates = RolePermissionTemplate.objects.count()
    
    print(f"✓ Seeded {total_permissions} permissions")
    print(f"✓ Seeded {total_templates} role templates")
    
    # Test specific permissions exist
    test_permissions = [
        ('loans', 'view_applications'),
        ('clients', 'create_new'),
        ('reports', 'export_pdf'),
        ('dashboard', 'view_overview'),
    ]
    
    for page, action in test_permissions:
        perm = PagePermission.objects.filter(page_name=page, action_code=action).first()
        if perm:
            print(f"✓ Found permission: {page}.{action}")
        else:
            print(f"✗ Missing permission: {page}.{action}")


def test_role_permissions():
    """Test role permission assignments"""
    print("\nTesting role permissions...")
    
    roles = ['admin', 'team_leader', 'loan_officer', 'secretary', 'auditor']
    
    for role in roles:
        templates = RolePermissionTemplate.objects.filter(role=role)
        allowed_count = templates.filter(is_allowed=True).count()
        total_count = templates.count()
        
        print(f"✓ {role}: {allowed_count}/{total_count} permissions granted")
        
        # Test specific role permissions
        if role == 'admin':
            # Admin should have all permissions
            admin_permissions = templates.filter(is_allowed=True).count()
            total_permissions = PagePermission.objects.count()
            if admin_permissions == total_permissions:
                print(f"  ✓ Admin has all {total_permissions} permissions")
            else:
                print(f"  ✗ Admin missing permissions: {total_permissions - admin_permissions}")
        
        elif role == 'auditor':
            # Auditor should have no create/edit/delete permissions
            critical_templates = templates.filter(
                page_permission__is_critical=True,
                is_allowed=True
            )
            if critical_templates.count() == 0:
                print(f"  ✓ Auditor has no critical permissions")
            else:
                print(f"  ✗ Auditor has {critical_templates.count()} critical permissions")


def test_permission_categories():
    """Test permission categorization"""
    print("\nTesting permission categories...")
    
    categories = ['view', 'create', 'edit', 'delete', 'approve', 'export', 'manage', 'process']
    
    for category in categories:
        count = PagePermission.objects.filter(category=category).count()
        print(f"✓ {category.capitalize()}: {count} permissions")
    
    # Test critical permissions
    critical_count = PagePermission.objects.filter(is_critical=True).count()
    print(f"✓ Critical permissions: {critical_count}")


def test_page_coverage():
    """Test that all expected pages have permissions"""
    print("\nTesting page coverage...")
    
    expected_pages = ['loans', 'clients', 'reports', 'dashboard', 'repayments', 'documents', 'settings']
    
    for page in expected_pages:
        count = PagePermission.objects.filter(page_name=page).count()
        if count > 0:
            print(f"✓ {page}: {count} permissions")
        else:
            print(f"✗ {page}: No permissions found")


def main():
    """Run all tests"""
    print("=== Granular Permissions Test Suite ===\n")
    
    try:
        test_permission_seeding()
        test_role_permissions()
        test_permission_categories()
        test_page_coverage()
        
        print("\n=== Test Summary ===")
        print("✓ All tests completed successfully")
        print("✓ Granular permissions system is properly configured")
        
        # Run verification command
        print("\nRunning verification command...")
        call_command('verify_permissions')
        
    except Exception as e:
        print(f"\n✗ Test failed with error: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()