from django.contrib.auth.models import Group, Permission
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Create Django groups for Casdoor SSO integration"

    def handle(self, *args, **options):
        groups_config = {
            "View Only": {"permissions": ["view"]},
            "Staff": {"permissions": ["view", "add", "change"]},
            "SME": {"permissions": ["view", "add", "change"]},
            "Admin": {"permissions": ["view", "add", "change", "delete"]},
        }

        models_to_permission = [
            # themis
            "userprofile",
            "userapikey",
            "usernotification",
            # library
            "ingestjob",
            # llm_manager
            "llmapi",
            "llmmodel",
            "llmusage",
        ]

        for group_name, config in groups_config.items():
            group, created = Group.objects.get_or_create(name=group_name)
            status = "Created" if created else "Exists"
            self.stdout.write(f"{status}: {group_name}")

            for perm_prefix in config["permissions"]:
                for model in models_to_permission:
                    try:
                        perm = Permission.objects.get(
                            codename=f"{perm_prefix}_{model}"
                        )
                        group.permissions.add(perm)
                    except Permission.DoesNotExist:
                        pass

        self.stdout.write(self.style.SUCCESS("SSO groups created successfully"))
