"""
Management command to verify that all permissions are properly seeded
"""
from django.core.management.base import BaseCommand
from django.db.models import Count, Q
from users.enhanced_permissions_models import PagePermission, RolePermissionTemplate


class Command(BaseCommand):
    help = 'Verify that all permissions and role templates are properly seeded'

    def handle(self, *args, **options):
        self.stdout.write('Verifying permission system setup...')
        
        # Check page permissions
        self.verify_page_permissions()
        
        # Check role templates
        self.verify_role_templates()
        
        # Check permission coverage
        self.verify_permission_coverage()
        
        self.stdout.write(
            self.style.SUCCESS('Permission system verification complete')
        )

    def verify_page_permissions(self):
        """Verify page permissions are properly seeded"""
        self.stdout.write('\n=== Page Permissions Verification ===')
        
        pages = ['loans', 'clients', 'reports', 'dashboard', 'repayments', 'documents', 'settings']
        
        for page in pages:
            count = PagePermission.objects.filter(page_name=page).count()
            self.stdout.write(f'{page.capitalize()} page: {count} permissions')
            
            # Show breakdown by category
            categories = PagePermission.objects.filter(page_name=page).values('category').annotate(
                count=Count('category')
            ).order_by('category')
            
            for cat in categories:
                self.stdout.write(f'  - {cat["category"]}: {cat["count"]} permissions')
        
        total_permissions = PagePermission.objects.count()
        critical_permissions = PagePermission.objects.filter(is_critical=True).count()
        
        self.stdout.write(f'\nTotal permissions: {total_permissions}')
        self.stdout.write(f'Critical permissions: {critical_permissions}')

    def verify_role_templates(self):
        """Verify role permission templates are properly seeded"""
        self.stdout.write('\n=== Role Permission Templates Verification ===')
        
        roles = ['admin', 'team_leader', 'loan_officer', 'secretary', 'auditor']
        
        for role in roles:
            total_templates = RolePermissionTemplate.objects.filter(role=role).count()
            allowed_templates = RolePermissionTemplate.objects.filter(
                role=role, is_allowed=True
            ).count()
            
            self.stdout.write(f'{role.replace("_", " ").title()}: {allowed_templates}/{total_templates} permissions granted')
            
            # Show breakdown by page
            pages = RolePermissionTemplate.objects.filter(role=role).values(
                'page_permission__page_name'
            ).annotate(
                total=Count('page_permission__page_name'),
                allowed=Count('page_permission__page_name', filter=Q(is_allowed=True))
            ).order_by('page_permission__page_name')
            
            for page in pages:
                page_name = page['page_permission__page_name']
                allowed = page['allowed'] if 'allowed' in page else 0
                total = page['total']
                self.stdout.write(f'  - {page_name}: {allowed}/{total}')

    def verify_permission_coverage(self):
        """Verify that all permissions have role template coverage"""
        self.stdout.write('\n=== Permission Coverage Verification ===')
        
        # Check for permissions without any role templates
        permissions_without_templates = PagePermission.objects.filter(
            rolepermissiontemplate__isnull=True
        ).distinct()
        
        if permissions_without_templates.exists():
            self.stdout.write(
                self.style.WARNING('Permissions without role templates:')
            )
            for perm in permissions_without_templates:
                self.stdout.write(f'  - {perm.page_name}.{perm.action_code}')
        else:
            self.stdout.write(
                self.style.SUCCESS('All permissions have role template coverage')
            )
        
        # Check for role templates without permissions (orphaned templates)
        orphaned_templates = RolePermissionTemplate.objects.filter(
            page_permission__isnull=True
        )
        
        if orphaned_templates.exists():
            self.stdout.write(
                self.style.WARNING('Orphaned role templates found:')
            )
            for template in orphaned_templates:
                self.stdout.write(f'  - {template.role}: {template.id}')
        else:
            self.stdout.write(
                self.style.SUCCESS('No orphaned role templates found')
            )
        
        # Show summary statistics
        self.stdout.write('\n=== Summary Statistics ===')
        total_permissions = PagePermission.objects.count()
        total_templates = RolePermissionTemplate.objects.count()
        active_permissions = PagePermission.objects.filter(is_active=True).count()
        
        self.stdout.write(f'Total permissions defined: {total_permissions}')
        self.stdout.write(f'Active permissions: {active_permissions}')
        self.stdout.write(f'Total role templates: {total_templates}')
        self.stdout.write(f'Average templates per permission: {total_templates / total_permissions:.1f}')

    def show_permission_matrix(self):
        """Show a detailed permission matrix"""
        self.stdout.write('\n=== Permission Matrix ===')
        
        roles = ['admin', 'team_leader', 'loan_officer', 'secretary', 'auditor']
        pages = ['loans', 'clients', 'reports', 'dashboard', 'repayments', 'documents', 'settings']
        
        # Header
        header = f"{'Permission':<40}"
        for role in roles:
            header += f"{role.replace('_', ' ').title():<15}"
        self.stdout.write(header)
        self.stdout.write('=' * len(header))
        
        for page in pages:
            permissions = PagePermission.objects.filter(page_name=page).order_by('action_code')
            
            for perm in permissions:
                row = f"{perm.page_name}.{perm.action_code}"[:39].ljust(40)
                
                for role in roles:
                    try:
                        template = RolePermissionTemplate.objects.get(
                            role=role, page_permission=perm
                        )
                        status = "✓" if template.is_allowed else "✗"
                    except RolePermissionTemplate.DoesNotExist:
                        status = "-"
                    
                    row += f"{status:<15}"
                
                self.stdout.write(row)