from django.core.management.base import BaseCommand
from users.models import RolePermission, DefaultRolePermission


class Command(BaseCommand):
    help = 'Set up enhanced role-based permissions with comprehensive modules and actions'

    def handle(self, *args, **options):
        # Clear existing permissions
        RolePermission.objects.all().delete()
        DefaultRolePermission.objects.all().delete()
        
        # Define comprehensive default permissions for each role
        role_permissions = {
            'admin': {
                # Admin gets all permissions
                'dashboard': ['view', 'manage'],
                'users': ['view', 'create', 'edit', 'delete', 'manage', 'suspend', 'activate', 'verify'],
                'clients': ['view', 'create', 'edit', 'delete', 'manage', 'assign', 'reassign', 'suspend', 'activate', 'verify'],
                'loans': ['view', 'create', 'edit', 'delete', 'approve', 'reject', 'manage'],
                'applications': ['view', 'create', 'edit', 'delete', 'approve', 'reject', 'manage'],
                'repayments': ['view', 'create', 'edit', 'delete', 'manage', 'verify'],
                'reports': ['view', 'create', 'edit', 'delete', 'export', 'import', 'manage', 'generate'],
                'documents': ['view', 'create', 'edit', 'delete', 'upload', 'download', 'share', 'manage'],
                'settings': ['view', 'create', 'edit', 'delete', 'manage'],
                'notifications': ['view', 'create', 'edit', 'delete', 'manage'],
                'audit': ['view', 'export', 'manage'],
                'kyc': ['view', 'create', 'edit', 'delete', 'verify', 'approve', 'reject', 'manage'],
                'payments': ['view', 'create', 'edit', 'delete', 'verify', 'approve', 'manage'],
                'communications': ['view', 'create', 'edit', 'delete', 'manage'],
                'portfolio': ['view', 'create', 'edit', 'delete', 'manage', 'assign', 'reassign'],
                'receipts': ['view', 'create', 'edit', 'delete', 'generate', 'print', 'manage'],
                'statements': ['view', 'create', 'edit', 'delete', 'generate', 'print', 'manage'],
                'media': ['view', 'create', 'edit', 'delete', 'upload', 'download', 'manage'],
                'backup': ['view', 'create', 'manage'],
                'system': ['view', 'create', 'edit', 'delete', 'manage'],
            },
            'team_leader': {
                'dashboard': ['view'],
                'users': ['view', 'create', 'edit', 'suspend', 'activate'],
                'clients': ['view', 'create', 'edit', 'assign', 'reassign', 'verify'],
                'loans': ['view', 'create', 'edit', 'approve', 'reject'],
                'applications': ['view', 'create', 'edit', 'approve', 'reject'],
                'repayments': ['view', 'create', 'edit', 'verify'],
                'reports': ['view', 'export', 'generate'],
                'documents': ['view', 'create', 'edit', 'upload', 'download', 'share'],
                'settings': ['view'],
                'notifications': ['view', 'create', 'edit'],
                'audit': ['view'],
                'kyc': ['view', 'create', 'edit', 'verify', 'approve', 'reject'],
                'payments': ['view', 'create', 'edit', 'verify'],
                'communications': ['view', 'create', 'edit'],
                'portfolio': ['view', 'manage', 'assign', 'reassign'],
                'receipts': ['view', 'create', 'edit', 'generate', 'print'],
                'statements': ['view', 'create', 'edit', 'generate', 'print'],
                'media': ['view', 'upload', 'download'],
                'backup': ['view'],
                'system': ['view'],
            },
            'loan_officer': {
                'dashboard': ['view'],
                'users': ['view'],
                'clients': ['view', 'create', 'edit', 'verify'],
                'loans': ['view', 'create', 'edit'],
                'applications': ['view', 'create', 'edit'],
                'repayments': ['view', 'create', 'edit'],
                'reports': ['view', 'export'],
                'documents': ['view', 'create', 'edit', 'upload', 'download'],
                'settings': ['view'],
                'notifications': ['view', 'create'],
                'audit': [],
                'kyc': ['view', 'create', 'edit', 'verify'],
                'payments': ['view', 'create', 'edit'],
                'communications': ['view', 'create'],
                'portfolio': ['view'],
                'receipts': ['view', 'create', 'generate', 'print'],
                'statements': ['view', 'generate', 'print'],
                'media': ['view', 'upload'],
                'backup': [],
                'system': [],
            },
            'secretary': {
                'dashboard': ['view'],
                'users': ['view'],
                'clients': ['view', 'create', 'edit'],
                'loans': ['view'],
                'applications': ['view', 'create'],
                'repayments': ['view'],
                'reports': ['view'],
                'documents': ['view', 'create', 'edit', 'upload', 'download'],
                'settings': ['view'],
                'notifications': ['view', 'create', 'edit'],
                'audit': [],
                'kyc': ['view', 'create', 'edit'],
                'payments': ['view'],
                'communications': ['view', 'create', 'edit'],
                'portfolio': ['view'],
                'receipts': ['view', 'print'],
                'statements': ['view', 'print'],
                'media': ['view', 'upload'],
                'backup': [],
                'system': [],
            },
            'borrower': {
                'dashboard': ['view'],
                'users': [],
                'clients': [],
                'loans': ['view'],
                'applications': ['view', 'create'],
                'repayments': ['view'],
                'reports': [],
                'documents': ['view', 'upload'],
                'settings': [],
                'notifications': ['view'],
                'audit': [],
                'kyc': ['view', 'create', 'edit'],
                'payments': ['view'],
                'communications': ['view'],
                'portfolio': [],
                'receipts': ['view', 'download'],
                'statements': ['view', 'download'],
                'media': ['view'],
                'backup': [],
                'system': [],
            }
        }

        # Create default permissions
        default_count = 0
        for role, modules in role_permissions.items():
            for module, actions in modules.items():
                # Get all possible actions for this module
                all_actions = [choice[0] for choice in RolePermission.ACTION_CHOICES]
                
                for action in all_actions:
                    is_allowed = action in actions
                    
                    # Create default permission
                    DefaultRolePermission.objects.create(
                        role=role,
                        module=module,
                        action=action,
                        is_allowed=is_allowed,
                        description=f"Default {action} permission for {module} module"
                    )
                    default_count += 1

        # Create role permissions based on defaults
        role_count = 0
        for default_perm in DefaultRolePermission.objects.all():
            RolePermission.objects.create(
                role=default_perm.role,
                module=default_perm.module,
                action=default_perm.action,
                is_allowed=default_perm.is_allowed,
                is_default=True
            )
            role_count += 1

        self.stdout.write(
            self.style.SUCCESS(
                f'Successfully created {default_count} default permissions and {role_count} role permissions'
            )
        )
        
        # Display summary
        for role in role_permissions.keys():
            default_count = DefaultRolePermission.objects.filter(role=role).count()
            allowed_count = DefaultRolePermission.objects.filter(role=role, is_allowed=True).count()
            self.stdout.write(f"  {role}: {allowed_count}/{default_count} permissions allowed")
        
        self.stdout.write(
            self.style.SUCCESS(
                '\nEnhanced permission system setup complete!'
            )
        )
        
        self.stdout.write(
            self.style.WARNING(
                '\nNext steps:'
            )
        )
        self.stdout.write('1. Run migrations if you haven\'t already')
        self.stdout.write('2. Visit /users/staff/dashboard/ to manage staff permissions')
        self.stdout.write('3. Use /users/staff/default-permissions/ to customize role defaults')
        self.stdout.write('4. Individual staff permissions can be managed from the staff list')