"""
Management command to create admin permission groups
"""
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType


class Command(BaseCommand):
    help = 'Create admin permission groups with appropriate permissions'

    def handle(self, *args, **options):
        self.stdout.write('Creating admin permission groups...')
        
        # Define permission groups
        groups_permissions = {
            'Content Manager': {
                'description': 'Can manage content, tasks, keywords, and clusters',
                'models': [
                    ('writer', 'content'),
                    ('writer', 'tasks'),
                    ('writer', 'images'),
                    ('planner', 'keywords'),
                    ('planner', 'clusters'),
                    ('planner', 'contentideas'),
                    ('system', 'aiprompt'),
                    ('system', 'strategy'),
                    ('system', 'authorprofile'),
                    ('system', 'contenttemplate'),
                ],
                'permissions': ['add', 'change', 'view'],  # No delete
            },
            'Billing Admin': {
                'description': 'Can manage payments, invoices, and credit transactions',
                'models': [
                    ('billing', 'payment'),
                    ('billing', 'invoice'),
                    ('billing', 'credittransaction'),
                    ('billing', 'creditusagelog'),
                    ('billing', 'creditpackage'),
                    ('billing', 'creditcostconfig'),
                    ('igny8_core_auth', 'account'),  # View accounts for billing context
                ],
                'permissions': ['add', 'change', 'view', 'delete'],
            },
            'Support Agent': {
                'description': 'Can view content, assist users, manage integrations',
                'models': [
                    ('writer', 'content'),
                    ('writer', 'tasks'),
                    ('planner', 'keywords'),
                    ('planner', 'clusters'),
                    ('integration', 'siteintegration'),
                    ('integration', 'syncevent'),
                    ('publishing', 'publishingrecord'),
                    ('automation', 'automationrun'),
                    ('igny8_core_auth', 'account'),
                    ('igny8_core_auth', 'site'),
                    ('igny8_core_auth', 'user'),
                ],
                'permissions': ['view'],  # Read-only
            },
        }
        
        created_count = 0
        updated_count = 0
        
        for group_name, config in groups_permissions.items():
            group, created = Group.objects.get_or_create(name=group_name)
            
            if created:
                self.stdout.write(self.style.SUCCESS(f'✓ Created group: {group_name}'))
                created_count += 1
            else:
                self.stdout.write(f'  Group already exists: {group_name}')
                updated_count += 1
            
            # Clear existing permissions
            group.permissions.clear()
            
            # Add permissions for each model
            permissions_added = 0
            for app_label, model_name in config['models']:
                try:
                    content_type = ContentType.objects.get(app_label=app_label, model=model_name)
                    
                    for perm_type in config['permissions']:
                        try:
                            permission = Permission.objects.get(
                                content_type=content_type,
                                codename=f'{perm_type}_{model_name}'
                            )
                            group.permissions.add(permission)
                            permissions_added += 1
                        except Permission.DoesNotExist:
                            self.stdout.write(
                                self.style.WARNING(
                                    f'  ! Permission not found: {perm_type}_{model_name}'
                                )
                            )
                except ContentType.DoesNotExist:
                    self.stdout.write(
                        self.style.WARNING(
                            f'  ! ContentType not found: {app_label}.{model_name}'
                        )
                    )
            
            self.stdout.write(f'    Added {permissions_added} permissions to {group_name}')
        
        self.stdout.write('')
        self.stdout.write(self.style.SUCCESS(f'✓ Created {created_count} new group(s)'))
        self.stdout.write(self.style.SUCCESS(f'✓ Updated {updated_count} existing group(s)'))
        self.stdout.write('')
        self.stdout.write('Permission groups created successfully!')
        self.stdout.write('')
        self.stdout.write('Group descriptions:')
        for group_name, config in groups_permissions.items():
            self.stdout.write(f'  • {group_name}: {config["description"]}')
