"""
ViewSets for the automations app.

Provides API endpoints for:
- AutomationViewSet: List available automations from registry
- AutomationTemplateViewSet: CRUD for automation templates
- AutomationInstallationViewSet: Manage installed automations
- EventAutomationViewSet: Attach automations to events
- GlobalEventAutomationViewSet: Global automation rules
"""

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from django.core.exceptions import ValidationError as DjangoValidationError

from .models import (
    AutomationTemplate,
    AutomationInstallation,
    EventAutomation,
    GlobalEventAutomation,
)
from .serializers import (
    AutomationInfoSerializer,
    AutomationTemplateSerializer,
    AutomationTemplateListSerializer,
    AutomationInstallationSerializer,
    EventAutomationSerializer,
    GlobalEventAutomationSerializer,
)
from smoothschedule.scheduling.schedule.models import ScheduledTask


class AutomationViewSet(viewsets.ViewSet):
    """
    API endpoint for listing available automations from the registry.

    Features:
    - List all registered automations
    - Get automation details
    - List automations by category
    """
    permission_classes = [AllowAny]  # TODO: Change to IsAuthenticated for production

    def list(self, request):
        """List all available automations"""
        from .registry import registry

        automations = registry.list_all()
        serializer = AutomationInfoSerializer(automations, many=True)

        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def by_category(self, request):
        """List automations grouped by category"""
        from .registry import registry

        automations_by_category = registry.list_by_category()

        return Response(automations_by_category)

    def retrieve(self, request, pk=None):
        """Get details for a specific automation"""
        from .registry import registry

        automation_class = registry.get(pk)
        if not automation_class:
            return Response(
                {'error': f"Automation '{pk}' not found"},
                status=status.HTTP_404_NOT_FOUND
            )

        automation_info = {
            'name': automation_class.name,
            'display_name': automation_class.display_name,
            'description': automation_class.description,
            'category': automation_class.category,
            'config_schema': automation_class.config_schema,
        }

        serializer = AutomationInfoSerializer(automation_info)
        return Response(serializer.data)


class AutomationTemplateViewSet(viewsets.ModelViewSet):
    """
    API endpoint for managing automation templates.

    Features:
    - List all automation templates (filtered by visibility)
    - Create new automation templates
    - Update existing templates
    - Delete templates
    - Publish to marketplace
    - Unpublish from marketplace
    - Install a template as a ScheduledTask
    - Request approval (for marketplace publishing)
    - Approve/reject templates (platform admins only)

    Permissions:
    - Marketplace view: Always accessible (for discovery)
    - My Automations view: Requires can_use_automations feature
    - Install action: Requires can_use_automations feature
    - Create: Requires can_use_automations AND can_create_automations features
    """
    queryset = AutomationTemplate.objects.all()
    serializer_class = AutomationTemplateSerializer
    permission_classes = [AllowAny]  # TODO: Change to IsAuthenticated for production
    ordering = ['-created_at']
    filterset_fields = ['visibility', 'category', 'is_approved']
    search_fields = ['name', 'short_description', 'description', 'tags']

    def _has_automations_permission(self):
        """Check if tenant has permission to use automations."""
        tenant = getattr(self.request, 'tenant', None)
        if tenant:
            # Check for new feature name, fall back to old name for compatibility
            return tenant.has_feature('can_use_automations') or tenant.has_feature('can_use_automations')
        return True  # Allow if no tenant context

    def get_queryset(self):
        """
        Filter templates based on user permissions.

        - Marketplace view: Only approved PUBLIC templates (always accessible)
        - My Automations: User's own templates (requires can_use_automations)
        - Platform admins: All templates
        """
        queryset = super().get_queryset()
        view_mode = self.request.query_params.get('view', 'marketplace')

        if view_mode == 'marketplace':
            # Public marketplace - platform official + approved public templates
            # Always accessible for discovery/marketing purposes
            from django.db.models import Q
            queryset = queryset.filter(
                Q(visibility=AutomationTemplate.Visibility.PLATFORM) |
                Q(visibility=AutomationTemplate.Visibility.PUBLIC, is_approved=True)
            )
        elif view_mode == 'my_automations' or view_mode == 'my_plugins':
            # User's own templates - requires automation permission
            if not self._has_automations_permission():
                queryset = queryset.none()
            elif self.request.user.is_authenticated:
                queryset = queryset.filter(author=self.request.user)
            else:
                queryset = queryset.none()
        elif view_mode == 'platform':
            # Platform official automations - always accessible for discovery
            queryset = queryset.filter(visibility=AutomationTemplate.Visibility.PLATFORM)
        # else: all templates (for platform admins)

        # Filter by category if provided
        category = self.request.query_params.get('category')
        if category:
            queryset = queryset.filter(category=category)

        # Filter by search query
        search = self.request.query_params.get('search')
        if search:
            from django.db.models import Q
            queryset = queryset.filter(
                Q(name__icontains=search) |
                Q(short_description__icontains=search) |
                Q(description__icontains=search) |
                Q(tags__icontains=search)
            )

        return queryset

    def get_serializer_class(self):
        """Use lightweight serializer for list view"""
        if self.action == 'list':
            return AutomationTemplateListSerializer
        return AutomationTemplateSerializer

    def perform_create(self, serializer):
        """Set author and extract template variables on create"""
        from smoothschedule.scheduling.schedule.template_parser import TemplateVariableParser
        from rest_framework.exceptions import PermissionDenied

        # Check permission to use automations first
        tenant = getattr(self.request, 'tenant', None)
        if tenant and not (tenant.has_feature('can_use_automations') or tenant.has_feature('can_use_automations')):
            raise PermissionDenied(
                "Your current plan does not include Automation access. "
                "Please upgrade your subscription to use automations."
            )

        # Check permission to create automations
        if tenant and not (tenant.has_feature('can_create_automations') or tenant.has_feature('can_create_automations')):
            raise PermissionDenied(
                "Your current plan does not include Automation Creation. "
                "Please upgrade your subscription to create custom automations."
            )

        plugin_code = serializer.validated_data.get('plugin_code', '')
        template_vars = TemplateVariableParser.extract_variables(plugin_code)

        # Convert to dict format expected by model
        template_vars_dict = {var['name']: var for var in template_vars}

        serializer.save(
            author=self.request.user if self.request.user.is_authenticated else None,
            template_variables=template_vars_dict
        )

    @action(detail=True, methods=['post'])
    def publish(self, request, pk=None):
        """Publish template to marketplace (requires approval)"""
        template = self.get_object()

        # Check ownership
        if template.author != request.user:
            return Response(
                {'error': 'You can only publish your own templates'},
                status=status.HTTP_403_FORBIDDEN
            )

        # Check if approved
        if not template.is_approved:
            return Response(
                {'error': 'Template must be approved before publishing to marketplace'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # Publish
        try:
            template.publish_to_marketplace(request.user)
            return Response({
                'message': 'Template published to marketplace successfully',
                'slug': template.slug
            })
        except DjangoValidationError as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def unpublish(self, request, pk=None):
        """Unpublish template from marketplace"""
        template = self.get_object()

        # Check ownership
        if template.author != request.user:
            return Response(
                {'error': 'You can only unpublish your own templates'},
                status=status.HTTP_403_FORBIDDEN
            )

        template.unpublish_from_marketplace()
        return Response({
            'message': 'Template unpublished from marketplace successfully'
        })

    @action(detail=True, methods=['post'])
    def install(self, request, pk=None):
        """
        Install an automation template as a ScheduledTask.

        Expects:
        {
            "name": "Task Name",
            "description": "Task Description",
            "config_values": {"variable1": "value1", ...},
            "schedule_type": "CRON",
            "cron_expression": "0 0 * * *"
        }
        """
        # Check permission to use automations
        tenant = getattr(request, 'tenant', None)
        if tenant and not (tenant.has_feature('can_use_automations') or tenant.has_feature('can_use_automations')):
            return Response(
                {'error': 'Your current plan does not include Automation access. Please upgrade your subscription to install automations.'},
                status=status.HTTP_403_FORBIDDEN
            )

        template = self.get_object()

        # Check if template is accessible
        if template.visibility == AutomationTemplate.Visibility.PRIVATE:
            if not request.user.is_authenticated or template.author != request.user:
                return Response(
                    {'error': 'This template is private'},
                    status=status.HTTP_403_FORBIDDEN
                )
        elif template.visibility == AutomationTemplate.Visibility.PUBLIC:
            if not template.is_approved:
                return Response(
                    {'error': 'This template has not been approved'},
                    status=status.HTTP_400_BAD_REQUEST
                )

        # Create ScheduledTask from template
        from smoothschedule.scheduling.schedule.template_parser import TemplateVariableParser

        name = request.data.get('name')
        description = request.data.get('description', '')
        config_values = request.data.get('config_values', {})
        schedule_type = request.data.get('schedule_type')
        cron_expression = request.data.get('cron_expression')
        interval_minutes = request.data.get('interval_minutes')
        run_at = request.data.get('run_at')

        if not name:
            return Response(
                {'error': 'name is required'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # Compile template with config values
        try:
            compiled_code = TemplateVariableParser.compile_template(
                template.plugin_code,
                config_values,
                context={}  # TODO: Add business context
            )
        except ValueError as e:
            return Response(
                {'error': f'Configuration error: {str(e)}'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # Create ScheduledTask
        scheduled_task = ScheduledTask.objects.create(
            name=name,
            description=description,
            plugin_name='custom_script',  # Use custom script automation
            plugin_code=compiled_code,
            plugin_config={},
            schedule_type=schedule_type,
            cron_expression=cron_expression,
            interval_minutes=interval_minutes,
            run_at=run_at,
            status=ScheduledTask.Status.ACTIVE,
            created_by=request.user if request.user.is_authenticated else None
        )

        # Create AutomationInstallation record
        installation = AutomationInstallation.objects.create(
            template=template,
            scheduled_task=scheduled_task,
            installed_by=request.user if request.user.is_authenticated else None,
            config_values=config_values,
            template_version_hash=template.plugin_code_hash
        )

        # Increment install count
        template.install_count += 1
        template.save(update_fields=['install_count'])

        return Response({
            'message': 'Automation installed successfully',
            'scheduled_task_id': scheduled_task.id,
            'installation_id': installation.id
        }, status=status.HTTP_201_CREATED)

    @action(detail=True, methods=['post'])
    def request_approval(self, request, pk=None):
        """Request approval for marketplace publishing"""
        template = self.get_object()

        # Check ownership
        if template.author != request.user:
            return Response(
                {'error': 'You can only request approval for your own templates'},
                status=status.HTTP_403_FORBIDDEN
            )

        # Check if already approved or pending
        if template.is_approved:
            return Response(
                {'error': 'Template is already approved'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # Validate automation code
        validation = template.can_be_published()
        if not validation:
            from smoothschedule.scheduling.schedule.safe_scripting import validate_plugin_whitelist
            errors = validate_plugin_whitelist(template.plugin_code)
            return Response(
                {'error': 'Template has validation errors', 'errors': errors['errors']},
                status=status.HTTP_400_BAD_REQUEST
            )

        # TODO: Notify platform admins about approval request
        # For now, just return success
        return Response({
            'message': 'Approval requested successfully. A platform administrator will review your automation.',
            'template_id': template.id
        })

    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        """Approve template for marketplace (platform admins only)"""
        # TODO: Add permission check for platform admins
        # if not request.user.has_perm('can_approve_automations'):
        #     return Response({'error': 'Permission denied'}, status=status.HTTP_403_FORBIDDEN)

        template = self.get_object()

        if template.is_approved:
            return Response(
                {'error': 'Template is already approved'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # Validate automation code
        from smoothschedule.scheduling.schedule.safe_scripting import validate_plugin_whitelist
        validation = validate_plugin_whitelist(template.plugin_code, scheduled_task=None)

        if not validation['valid']:
            return Response(
                {'error': 'Template has validation errors', 'errors': validation['errors']},
                status=status.HTTP_400_BAD_REQUEST
            )

        # Approve
        from django.utils import timezone
        template.is_approved = True
        template.approved_by = request.user if request.user.is_authenticated else None
        template.approved_at = timezone.now()
        template.rejection_reason = ''
        template.save()

        return Response({
            'message': 'Template approved successfully',
            'template_id': template.id
        })

    @action(detail=True, methods=['post'])
    def reject(self, request, pk=None):
        """Reject template for marketplace (platform admins only)"""
        # TODO: Add permission check for platform admins
        # if not request.user.has_perm('can_approve_automations'):
        #     return Response({'error': 'Permission denied'}, status=status.HTTP_403_FORBIDDEN)

        template = self.get_object()
        reason = request.data.get('reason', 'No reason provided')

        template.is_approved = False
        template.rejection_reason = reason
        template.save()

        return Response({
            'message': 'Template rejected',
            'reason': reason
        })


class AutomationInstallationViewSet(viewsets.ModelViewSet):
    """
    API endpoint for managing automation installations.

    Features:
    - List user's installed automations
    - View installation details
    - Update installation (update to latest version)
    - Uninstall automation
    - Rate and review automation

    Permissions:
    - Requires can_use_automations feature for all operations
    """
    queryset = AutomationInstallation.objects.select_related('template', 'scheduled_task').all()
    serializer_class = AutomationInstallationSerializer
    permission_classes = [AllowAny]  # TODO: Change to IsAuthenticated for production
    ordering = ['-installed_at']

    def _check_automations_permission(self):
        """Check if tenant has permission to access automation installations."""
        from rest_framework.exceptions import PermissionDenied

        tenant = getattr(self.request, 'tenant', None)
        if tenant and not (tenant.has_feature('can_use_automations') or tenant.has_feature('can_use_automations')):
            raise PermissionDenied(
                "Your current plan does not include Automation access. "
                "Please upgrade your subscription to use automations."
            )

    def list(self, request, *args, **kwargs):
        """List automation installations with permission check."""
        self._check_automations_permission()
        return super().list(request, *args, **kwargs)

    def retrieve(self, request, *args, **kwargs):
        """Retrieve an automation installation with permission check."""
        self._check_automations_permission()
        return super().retrieve(request, *args, **kwargs)

    def get_queryset(self):
        """Return installations for current user/tenant"""
        queryset = super().get_queryset()

        # TODO: Filter by tenant when multi-tenancy is fully enabled
        # if self.request.user.is_authenticated and self.request.user.tenant:
        #     queryset = queryset.filter(scheduled_task__tenant=self.request.user.tenant)

        return queryset

    def perform_create(self, serializer):
        """Check permission to use automations before installing"""
        from rest_framework.exceptions import PermissionDenied

        # Check permission to use automations
        tenant = getattr(self.request, 'tenant', None)
        if tenant and not (tenant.has_feature('can_use_automations') or tenant.has_feature('can_use_automations')):
            raise PermissionDenied(
                "Your current plan does not include Automation access. "
                "Please upgrade your subscription to use automations."
            )

        serializer.save()

    @action(detail=True, methods=['post'])
    def update_to_latest(self, request, pk=None):
        """Update installed automation to latest template version"""
        installation = self.get_object()

        if not installation.has_update_available():
            return Response(
                {'error': 'No update available'},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            installation.update_to_latest()
            return Response({
                'message': 'Automation updated successfully',
                'new_version_hash': installation.template_version_hash
            })
        except DjangoValidationError as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def rate(self, request, pk=None):
        """Rate an installed automation"""
        installation = self.get_object()
        rating = request.data.get('rating')
        review = request.data.get('review', '')

        if not rating or not isinstance(rating, int) or rating < 1 or rating > 5:
            return Response(
                {'error': 'Rating must be an integer between 1 and 5'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # Update installation
        from django.utils import timezone
        installation.rating = rating
        installation.review = review
        installation.reviewed_at = timezone.now()
        installation.save()

        # Update template average rating
        if installation.template:
            template = installation.template
            ratings = AutomationInstallation.objects.filter(
                template=template,
                rating__isnull=False
            ).values_list('rating', flat=True)

            if ratings:
                from decimal import Decimal
                template.rating_average = Decimal(sum(ratings)) / Decimal(len(ratings))
                template.rating_count = len(ratings)
                template.save(update_fields=['rating_average', 'rating_count'])

        return Response({
            'message': 'Rating submitted successfully',
            'rating': rating
        })

    def destroy(self, request, *args, **kwargs):
        """Uninstall automation (delete ScheduledTask and Installation)"""
        installation = self.get_object()

        # Delete the scheduled task (this will cascade delete the installation)
        if installation.scheduled_task:
            installation.scheduled_task.delete()
        else:
            # If scheduled task was already deleted, just delete the installation
            installation.delete()

        return Response({
            'message': 'Automation uninstalled successfully'
        }, status=status.HTTP_204_NO_CONTENT)


class EventAutomationViewSet(viewsets.ModelViewSet):
    """
    API endpoint for managing automations attached to calendar events.

    This allows users to attach installed automations to events with configurable
    timing triggers (before start, at start, after end, on complete, etc.)

    Endpoints:
    - GET /api/event-automations/?event_id=X - List automations for an event
    - POST /api/event-automations/ - Attach automation to event
    - PATCH /api/event-automations/{id}/ - Update timing/trigger
    - DELETE /api/event-automations/{id}/ - Remove automation from event
    - POST /api/event-automations/{id}/toggle/ - Enable/disable automation
    """
    queryset = EventAutomation.objects.select_related(
        'event',
        'automation_installation',
        'automation_installation__template'
    ).all()
    serializer_class = EventAutomationSerializer
    permission_classes = [AllowAny]  # TODO: Change to IsAuthenticated

    def get_queryset(self):
        """Filter by event if specified"""
        queryset = super().get_queryset()

        event_id = self.request.query_params.get('event_id')
        if event_id:
            queryset = queryset.filter(event_id=event_id)

        return queryset.order_by('execution_order', 'created_at')

    def perform_create(self, serializer):
        """Check permission to use automations before attaching to event"""
        from rest_framework.exceptions import PermissionDenied

        tenant = getattr(self.request, 'tenant', None)
        if tenant and not (tenant.has_feature('can_use_automations') or tenant.has_feature('can_use_automations')):
            raise PermissionDenied(
                "Your current plan does not include Automation access. "
                "Please upgrade your subscription to use automations."
            )

        serializer.save()

    def list(self, request):
        """
        List event automations.

        Query params:
        - event_id: Filter by event (required for listing)
        """
        event_id = request.query_params.get('event_id')
        if not event_id:
            return Response({
                'error': 'event_id query parameter is required'
            }, status=status.HTTP_400_BAD_REQUEST)

        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def toggle(self, request, pk=None):
        """Toggle is_active status of an event automation"""
        event_automation = self.get_object()
        event_automation.is_active = not event_automation.is_active
        event_automation.save(update_fields=['is_active'])

        serializer = self.get_serializer(event_automation)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def triggers(self, request):
        """
        Get available trigger options for the UI.

        Returns trigger choices with human-readable labels and
        common offset presets.
        """
        return Response({
            'triggers': [
                {'value': choice[0], 'label': choice[1]}
                for choice in EventAutomation.Trigger.choices
            ],
            'offset_presets': [
                {'value': 0, 'label': 'Immediately'},
                {'value': 5, 'label': '5 minutes'},
                {'value': 10, 'label': '10 minutes'},
                {'value': 15, 'label': '15 minutes'},
                {'value': 30, 'label': '30 minutes'},
                {'value': 60, 'label': '1 hour'},
                {'value': 120, 'label': '2 hours'},
                {'value': 1440, 'label': '1 day'},
            ],
            'timing_groups': [
                {
                    'label': 'Before Event',
                    'triggers': ['before_start'],
                    'supports_offset': True,
                },
                {
                    'label': 'During Event',
                    'triggers': ['at_start', 'after_start'],
                    'supports_offset': True,
                },
                {
                    'label': 'After Event',
                    'triggers': ['after_end'],
                    'supports_offset': True,
                },
                {
                    'label': 'Status Changes',
                    'triggers': ['on_complete', 'on_cancel'],
                    'supports_offset': False,
                },
            ]
        })


class GlobalEventAutomationViewSet(viewsets.ModelViewSet):
    """
    API endpoint for managing global event automation rules.

    Global event automations automatically attach to ALL events - both existing
    events and new events as they are created.

    Use this for automation rules that should apply across the board, such as:
    - Sending confirmation emails for all appointments
    - Logging all event completions
    - Running cleanup after every event

    Endpoints:
    - GET /api/global-event-automations/ - List all global rules
    - POST /api/global-event-automations/ - Create rule (auto-applies to existing events)
    - GET /api/global-event-automations/{id}/ - Get rule details
    - PATCH /api/global-event-automations/{id}/ - Update rule
    - DELETE /api/global-event-automations/{id}/ - Delete rule
    - POST /api/global-event-automations/{id}/toggle/ - Enable/disable rule
    - POST /api/global-event-automations/{id}/reapply/ - Reapply to all events
    """
    queryset = GlobalEventAutomation.objects.select_related(
        'automation_installation',
        'automation_installation__template',
        'created_by'
    ).all()
    serializer_class = GlobalEventAutomationSerializer
    permission_classes = [AllowAny]  # TODO: Change to IsAuthenticated

    def get_queryset(self):
        """Optionally filter by active status"""
        queryset = super().get_queryset()

        is_active = self.request.query_params.get('is_active')
        if is_active is not None:
            queryset = queryset.filter(is_active=is_active.lower() == 'true')

        return queryset.order_by('execution_order', 'created_at')

    def perform_create(self, serializer):
        """Check permission to use automations and set created_by on creation"""
        from rest_framework.exceptions import PermissionDenied

        tenant = getattr(self.request, 'tenant', None)
        if tenant and not (tenant.has_feature('can_use_automations') or tenant.has_feature('can_use_automations')):
            raise PermissionDenied(
                "Your current plan does not include Automation access. "
                "Please upgrade your subscription to use automations."
            )

        user = self.request.user if self.request.user.is_authenticated else None
        serializer.save(created_by=user)

    @action(detail=True, methods=['post'])
    def toggle(self, request, pk=None):
        """Toggle is_active status of a global event automation rule"""
        global_automation = self.get_object()
        global_automation.is_active = not global_automation.is_active
        global_automation.save(update_fields=['is_active', 'updated_at'])

        serializer = self.get_serializer(global_automation)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def reapply(self, request, pk=None):
        """
        Reapply this global rule to all events.

        Useful if:
        - Events were created while the rule was inactive
        - Automation attachments were manually removed
        """
        global_automation = self.get_object()

        if not global_automation.is_active:
            return Response({
                'error': 'Cannot reapply inactive rule. Enable it first.'
            }, status=status.HTTP_400_BAD_REQUEST)

        count = global_automation.apply_to_all_events()

        return Response({
            'message': f'Applied to {count} events',
            'events_affected': count
        })

    @action(detail=False, methods=['get'])
    def triggers(self, request):
        """
        Get available trigger options for the UI.

        Returns trigger choices with human-readable labels and
        common offset presets (same as EventAutomation).
        """
        return Response({
            'triggers': [
                {'value': choice[0], 'label': choice[1]}
                for choice in EventAutomation.Trigger.choices
            ],
            'offset_presets': [
                {'value': 0, 'label': 'Immediately'},
                {'value': 5, 'label': '5 minutes'},
                {'value': 10, 'label': '10 minutes'},
                {'value': 15, 'label': '15 minutes'},
                {'value': 30, 'label': '30 minutes'},
                {'value': 60, 'label': '1 hour'},
            ],
        })


# Backwards compatibility aliases (deprecated, will be removed in future)
PluginViewSet = AutomationViewSet
PluginTemplateViewSet = AutomationTemplateViewSet
PluginInstallationViewSet = AutomationInstallationViewSet
EventPluginViewSet = EventAutomationViewSet
GlobalEventPluginViewSet = GlobalEventAutomationViewSet
