import csv
from extras.scripts import Script, FileVar
from django.contrib.contenttypes.models import ContentType
from users.models import ObjectPermission
from django.contrib.auth.models import Group


class InitializeRolesScript(Script):
    csv_file = FileVar(description="Upload a CSV file with roles configuration")

    class Meta:
        name = "Initialize Roles and Permissions"
        description = "Create or update roles and permissions based on a CSV file."
        field_order = ['csv_file']

    def run(self, data, commit):
        csv_file = data['csv_file']

        # Required groups to ensure exist
        required_groups = ['SuperAccess', 'Administrator', 'Global Viewer', 'Overall Viewer']

        # Ensure groups exist
        for group_name in required_groups:
            group, created = Group.objects.get_or_create(name=group_name)
            if created:
                self.log_success(f"Group '{group_name}' created.")
            else:
                self.log_info(f"Group '{group_name}' already exists.")

        # Process the uploaded CSV file
        try:
            csv_data = csv_file.read().decode('utf-8').splitlines()
            reader = csv.DictReader(csv_data)

            for row in reader:
                # Read necessary columns from the CSV
                permission_name = row.get('Permission')
                groups = row.get('Groups', '').split(", ")
                app_label = row.get('app_label')
                model = row.get('model')

                # Configure the 'actions' field as a list with the permission name
                actions = [permission_name] if permission_name else ['view']

                # Get the corresponding content type
                try:
                    content_type = ContentType.objects.get(app_label=app_label, model=model)

                    # Create or update the permission
                    permission, created = ObjectPermission.objects.get_or_create(
                        name=f"{permission_name.capitalize()} {model.capitalize()}",
                        defaults={
                            'description': f"Automatically generated permission: {permission_name}",
                            'enabled': True,
                            'actions': actions
                        }
                    )

                    # Assign content types and groups only if the permission was newly created
                    if created:
                        permission.object_types.set([content_type])
                        for group_name in groups:
                            try:
                                group = Group.objects.get(name=group_name)
                                permission.groups.add(group)
                            except Group.DoesNotExist:
                                self.log_warning(f"Group '{group_name}' does not exist. Skipping...")

                    self.log_success(f"Permission '{permission_name}' created or updated for the model '{model}'.")

                except ContentType.DoesNotExist:
                    self.log_warning(f"ContentType '{app_label} > {model}' does not exist; skipping permission creation.")
        except Exception as e:
            self.log_error(f"Error processing the CSV file: {e}")