# Generated by Django 3.2.9 on 2022-08-13 05:33
from django.contrib.auth.models import Group, Permission
from django.core.management.sql import emit_post_migrate_signal
from django.conf import settings
import logging

from django.db import migrations

logger = logging.getLogger(__name__)

public_group_permissions = {
    settings.DEFAULT_PERMISSIONS_GROUP: [
        'create_corpus',
        'read_corpus',
        'update_corpus',
        'delete_corpus',
        'publish_corpus',
        'permission_corpus',

        'create_document',
        'read_document',
        'update_document',
        'delete_document',
        'publish_document',
        'permission_document',

        'create_labelset',
        'read_labelset',
        'update_labelset',
        'delete_labelset',
        'publish_labelset',
        'permission_labelset',

        'create_annotationlabel',
        'read_annotationlabel',
        'update_annotationlabel',
        'delete_annotationlabel',
        'publish_annotationlabel',
        'permission_annotationlabel',

        'create_relationship',
        'read_relationship',
        'update_relationship',
        'delete_relationship',
        'publish_relationship',
        'permission_relationship',

        'create_annotation',
        'read_annotation',
        'update_annotation',
        'delete_annotation',
        'publish_annotation',
        'permission_annotation',

        'create_userimport',
        'read_userimport',
        'update_userimport',
        'delete_userimport',
        'publish_userimport',
        'permission_userimport',

        'create_userexport',
        'read_userexport',
        'update_userexport',
        'delete_userexport',
        'publish_userexport',
        'permission_userexport',

        'create_gremlinengine',
        'read_gremlinengine',
        'update_gremlinengine',
        'delete_gremlinengine',
        'publish_gremlinengine',
        'permission_gremlinengine',

        'create_analyzer',
        'read_analyzer',
        'update_analyzer',
        'delete_analyzer',
        'publish_analyzer',
        'permission_analyzer'
    ]
}


def add_group_permissions(apps, schema_editor):
    """Create default public access group and assign permissions.

    Avoids triggering `emit_post_migrate_signal` here to prevent model/schema
    mismatches when new fields are added to the User model in later migrations.
    Post-migrate signals will be emitted by Django after all migrations anyway.
    """
    # Previously this migration called emit_post_migrate_signal to ensure
    # content types and permissions existed. This can cause issues when models
    # evolve. Allow the global post-migrate to handle it instead.

    for group in public_group_permissions:
        role, created = Group.objects.get_or_create(name=group)
        logger.info(f'{group} Group created')
        for perm in public_group_permissions[group]:
            try:
                logger.info(f'Permitting {group} to {perm}')
                role.permissions.add(Permission.objects.get(codename=perm))
            except Permission.DoesNotExist:
                # Permissions for some apps may not yet be created depending on migration order.
                # Skip missing permissions; they can be assigned later via admin or another migration.
                logger.warning(f"Permission '{perm}' does not exist yet; skipping assignment.")
        role.save()

    logger.info("Installation of default public access group COMPLETE!")


class Migration(migrations.Migration):

    dependencies = [
        ('users', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(add_group_permissions),
    ]
