#!/usr/bin/env python
"""Script to create admin permission groups"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'igny8_core.settings')
django.setup()

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType

groups_permissions = {
    'Content Manager': {
        'models': [
            ('writer', 'content'), ('writer', 'tasks'), ('writer', 'images'),
            ('planner', 'keywords'), ('planner', 'clusters'), ('planner', 'contentideas'),
        ],
        'permissions': ['add', 'change', 'view'],
    },
    'Billing Admin': {
        'models': [
            ('billing', 'payment'), ('billing', 'invoice'), ('billing', 'credittransaction'),
            ('billing', 'creditusagelog'), ('igny8_core_auth', 'account'),
        ],
        'permissions': ['add', 'change', 'view', 'delete'],
    },
    'Support Agent': {
        'models': [
            ('writer', 'content'), ('writer', 'tasks'),
            ('igny8_core_auth', 'account'), ('igny8_core_auth', 'site'),
        ],
        'permissions': ['view'],
    },
}

print('Creating admin permission groups...\n')

for group_name, config in groups_permissions.items():
    group, created = Group.objects.get_or_create(name=group_name)
    status = 'Created' if created else 'Updated'
    print(f'✓ {status} group: {group_name}')
    
    group.permissions.clear()
    added = 0
    
    for app_label, model_name in config['models']:
        try:
            ct = ContentType.objects.get(app_label=app_label, model=model_name)
            for perm_type in config['permissions']:
                try:
                    perm = Permission.objects.get(content_type=ct, codename=f'{perm_type}_{model_name}')
                    group.permissions.add(perm)
                    added += 1
                except Permission.DoesNotExist:
                    print(f'  ! Permission not found: {perm_type}_{model_name}')
        except ContentType.DoesNotExist:
            print(f'  ! ContentType not found: {app_label}.{model_name}')
    
    print(f'  Added {added} permissions')

print('\n✓ Permission groups created successfully!')
