"""
OpenAPI Schema Configuration for Stream Processing API

This module configures the OpenAPI schema generation for comprehensive
API documentation using drf-spectacular.
"""

from drf_spectacular.openapi import AutoSchema
from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample
from drf_spectacular.types import OpenApiTypes


class StreamProcessorAutoSchema(AutoSchema):
    """Custom schema generator for stream processor API."""
    
    def get_operation_id(self):
        """Generate operation ID for API endpoints."""
        if hasattr(self.view, 'action'):
            action = self.view.action
            if action:
                model_name = getattr(self.view, 'queryset', None)
                if model_name:
                    model_name = model_name.model._meta.object_name.lower()
                    return f"{model_name}_{action}"
        
        return super().get_operation_id()
    
    def get_tags(self):
        """Generate tags for API endpoint grouping."""
        if hasattr(self.view, 'queryset'):
            model_name = self.view.queryset.model._meta.verbose_name_plural
            return [model_name.title()]
        
        return super().get_tags()


# Common OpenAPI parameters for reuse
PAGINATION_PARAMETERS = [
    OpenApiParameter(
        name='page',
        type=OpenApiTypes.INT,
        location=OpenApiParameter.QUERY,
        description='Page number for pagination'
    ),
    OpenApiParameter(
        name='page_size',
        type=OpenApiTypes.INT,
        location=OpenApiParameter.QUERY,
        description='Number of items per page (max 100)'
    ),
]

ORDERING_PARAMETER = OpenApiParameter(
    name='ordering',
    type=OpenApiTypes.STR,
    location=OpenApiParameter.QUERY,
    description='Field to order results by. Prefix with "-" for descending order.'
)

SEARCH_PARAMETER = OpenApiParameter(
    name='search',
    type=OpenApiTypes.STR,
    location=OpenApiParameter.QUERY,
    description='Search term to filter results'
)

# Stream-specific parameters
CHANNEL_STATUS_PARAMETER = OpenApiParameter(
    name='is_active',
    type=OpenApiTypes.BOOL,
    location=OpenApiParameter.QUERY,
    description='Filter channels by active status'
)

SESSION_STATUS_PARAMETER = OpenApiParameter(
    name='status',
    type=OpenApiTypes.STR,
    location=OpenApiParameter.QUERY,
    description='Filter sessions by status',
    enum=['pending', 'active', 'processing', 'completed', 'failed', 'cancelled']
)

CHANNEL_FILTER_PARAMETER = OpenApiParameter(
    name='channel',
    type=OpenApiTypes.UUID,
    location=OpenApiParameter.QUERY,
    description='Filter by channel ID'
)

# Notification-specific parameters
NOTIFICATION_STATUS_PARAMETER = OpenApiParameter(
    name='status',
    type=OpenApiTypes.STR,
    location=OpenApiParameter.QUERY,
    description='Filter notifications by status',
    enum=['pending', 'processing', 'completed', 'failed']
)

NOTIFICATION_CHANNEL_PARAMETER = OpenApiParameter(
    name='channel',
    type=OpenApiTypes.UUID,
    location=OpenApiParameter.QUERY,
    description='Filter by notification channel ID'
)

TEMPLATE_TYPE_PARAMETER = OpenApiParameter(
    name='template_type',
    type=OpenApiTypes.STR,
    location=OpenApiParameter.QUERY,
    description='Filter by template type'
)

EVENT_TYPE_PARAMETER = OpenApiParameter(
    name='event_type',
    type=OpenApiTypes.STR,
    location=OpenApiParameter.QUERY,
    description='Filter by event type'
)

# Date range parameters
DATE_FROM_PARAMETER = OpenApiParameter(
    name='date_from',
    type=OpenApiTypes.DATE,
    location=OpenApiParameter.QUERY,
    description='Filter results from this date (YYYY-MM-DD)'
)

DATE_TO_PARAMETER = OpenApiParameter(
    name='date_to',
    type=OpenApiTypes.DATE,
    location=OpenApiParameter.QUERY,
    description='Filter results to this date (YYYY-MM-DD)'
)

# Common examples
CHANNEL_EXAMPLES = [
    OpenApiExample(
        'Basic Channel',
        summary='Basic streaming channel',
        description='A simple streaming channel configuration',
        value={
            'name': 'News Channel',
            'slug': 'news-channel',
            'hls_url': 'https://example.com/news/stream.m3u8',
            'description': 'Live news streaming channel',
            'output_directory': '/data/streams/news',
            'segment_duration': 6,
            'max_segments': 10
        }
    ),
    OpenApiExample(
        'High Quality Channel',
        summary='High quality streaming channel',
        description='Channel with custom video/audio configurations',
        value={
            'name': 'Premium Sports',
            'slug': 'premium-sports',
            'hls_url': 'https://example.com/sports/hd.m3u8',
            'description': 'Premium sports channel with HD quality',
            'output_directory': '/data/streams/sports',
            'segment_duration': 4,
            'max_segments': 15,
            'retry_attempts': 3,
            'retry_interval': 15
        }
    )
]

NOTIFICATION_CHANNEL_EXAMPLES = [
    OpenApiExample(
        'Telegram Channel',
        summary='Telegram notification channel',
        description='Configuration for Telegram bot notifications',
        value={
            'name': 'Telegram Alerts',
            'channel_type': 'telegram',
            'configuration': {
                'bot_token': '123456789:ABCdefGHIjklMNOpqrsTUVwxyz',
                'chat_id': '-1001234567890'
            }
        }
    ),
    OpenApiExample(
        'Email Channel',
        summary='Email notification channel',
        description='Configuration for SMTP email notifications',
        value={
            'name': 'Email Alerts',
            'channel_type': 'email',
            'configuration': {
                'smtp_host': 'smtp.gmail.com',
                'smtp_port': 587,
                'username': 'alerts@example.com',
                'password': 'app_password',
                'use_tls': True
            }
        }
    ),
    OpenApiExample(
        'Webhook Channel',
        summary='Webhook notification channel',
        description='Configuration for webhook notifications',
        value={
            'name': 'Webhook Alerts',
            'channel_type': 'webhook',
            'configuration': {
                'url': 'https://api.example.com/webhooks/alerts',
                'method': 'POST',
                'headers': {
                    'Authorization': 'Bearer your-api-token',
                    'Content-Type': 'application/json'
                }
            }
        }
    )
]

NOTIFICATION_TEMPLATE_EXAMPLES = [
    OpenApiExample(
        'Stream Started Template',
        summary='Template for stream start notifications',
        value={
            'name': 'Stream Started Alert',
            'template_type': 'stream_started',
            'subject_template': 'Stream {{channel_name}} Started',
            'body_template': 'The stream {{channel_name}} has started successfully at {{start_time}}. Session ID: {{session_id}}'
        }
    ),
    OpenApiExample(
        'Ad Break Template',
        summary='Template for ad break notifications',
        value={
            'name': 'Ad Break Detected',
            'template_type': 'ad_break_detected',
            'subject_template': 'Ad Break in {{channel_name}}',
            'body_template': 'Ad break detected in {{channel_name}} at {{detection_time}}. Confidence: {{confidence}}%'
        }
    )
]

# Error response examples
ERROR_EXAMPLES = {
    'validation_error': OpenApiExample(
        'Validation Error',
        summary='Input validation failed',
        value={
            'error': 'Validation failed',
            'details': {
                'hls_url': ['Invalid URL format.'],
                'segment_duration': ['Segment duration must be between 1 and 60 seconds.']
            }
        }
    ),
    'not_found': OpenApiExample(
        'Resource Not Found',
        summary='Requested resource does not exist',
        value={
            'error': 'Resource not found',
            'detail': 'Channel with ID 12345 does not exist.'
        }
    ),
    'permission_denied': OpenApiExample(
        'Permission Denied',
        summary='Insufficient permissions',
        value={
            'error': 'Permission denied',
            'detail': 'You do not have permission to perform this action.'
        }
    ),
    'rate_limited': OpenApiExample(
        'Rate Limited',
        summary='API rate limit exceeded',
        value={
            'error': 'Rate limit exceeded',
            'detail': 'Request was throttled. Expected available in 60 seconds.'
        }
    )
}

# Success response examples
SUCCESS_EXAMPLES = {
    'task_started': OpenApiExample(
        'Task Started',
        summary='Background task initiated successfully',
        value={
            'success': True,
            'task_id': 'abc123-def456-ghi789',
            'message': 'Stream capture task started successfully'
        }
    ),
    'operation_completed': OpenApiExample(
        'Operation Completed',
        summary='Operation completed successfully',
        value={
            'success': True,
            'message': 'Operation completed successfully'
        }
    )
}
