# -*- coding: utf-8 -*-
"""
Channel Management API v1 Views

This module contains API views for the channel management application.
"""

import json
import csv
import io
from datetime import datetime, timedelta
from django.http import HttpResponse, JsonResponse
from django.utils import timezone
from django.db.models import Q, Count, Avg, Sum
from django.core.cache import cache
from django.conf import settings
from django.core.files.base import ContentFile

from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend

from ...models import (
    Channel, ChannelZone, ChannelCodec, ChannelZoneRelation,
    EPGProgram, Jingle, JingleDetection, ChannelSchedule,
    IPSecConfiguration, OpenVPNConfiguration, WireGuardConfiguration
)
from .serializers import (
    ChannelListSerializer, ChannelDetailSerializer,
    ChannelZoneSerializer, ChannelCodecSerializer,
    ChannelZoneRelationSerializer, EPGProgramListSerializer,
    EPGProgramDetailSerializer, JingleListSerializer,
    JingleDetailSerializer, JingleDetectionSerializer,
    ChannelScheduleListSerializer, ChannelScheduleDetailSerializer,
    IPSecConfigurationSerializer, OpenVPNConfigurationSerializer,
    WireGuardConfigurationSerializer, BulkChannelActionSerializer,
    ChannelImportSerializer, ChannelStatisticsSerializer
)
from ...permissions import ChannelManagementPermissions
from ...tasks import (
    perform_channel_health_check, generate_jingle_fingerprint,
    update_channel_statistics, test_vpn_connection
)


class StandardResultsSetPagination(PageNumberPagination):
    """
    Standard pagination class for API views.
    """
    page_size = 20
    page_size_query_param = 'page_size'
    max_page_size = 100


# ============================================================================
# Channel ViewSets
# ============================================================================

class ChannelViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing channels.
    """
    queryset = Channel.objects.select_related('codec').prefetch_related(
        'zones', 'programs', 'jingles'
    )
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['name', 'description', 'channel_number']
    filterset_fields = ['category', 'status', 'is_hd', 'is_encrypted', 'language', 'country']
    ordering_fields = ['name', 'channel_number', 'created_at', 'updated_at']
    ordering = ['channel_number']
    
    def get_serializer_class(self):
        """
        Return appropriate serializer class based on action.
        """
        if self.action == 'list':
            return ChannelListSerializer
        return ChannelDetailSerializer
    
    def get_queryset(self):
        """
        Filter queryset based on user permissions and query parameters.
        """
        queryset = super().get_queryset()
        
        # Filter by zone if specified
        zone_id = self.request.query_params.get('zone', None)
        if zone_id:
            queryset = queryset.filter(zones__id=zone_id)
        
        # Filter by health status
        health_status = self.request.query_params.get('health_status', None)
        if health_status:
            queryset = queryset.filter(health_status=health_status)
        
        return queryset.distinct()
    
    @action(detail=True, methods=['post'])
    def health_check(self, request, pk=None):
        """
        Trigger health check for a specific channel.
        """
        channel = self.get_object()
        
        # Trigger async health check
        task = perform_channel_health_check.delay(channel.id)
        
        return Response({
            'message': 'Health check initiated',
            'task_id': task.id,
            'channel_id': channel.id
        })
    
    @action(detail=True, methods=['get'])
    def statistics(self, request, pk=None):
        """
        Get detailed statistics for a channel.
        """
        channel = self.get_object()
        
        # Check cache first
        cache_key = f'channel_stats_{channel.id}'
        stats = cache.get(cache_key)
        
        if not stats:
            stats = {
                'total_programs': channel.programs.count(),
                'total_jingles': channel.jingles.count(),
                'total_zones': channel.zones.count(),
                'avg_program_duration': channel.programs.aggregate(
                    avg_duration=Avg('duration')
                )['avg_duration'],
                'health_status': channel.health_status,
                'last_health_check': channel.last_health_check,
                'uptime_percentage': getattr(channel, 'uptime_percentage', None),
                'viewer_count': getattr(channel, 'viewer_count', 0),
            }
            
            # Cache for 5 minutes
            cache.set(cache_key, stats, 300)
        
        serializer = ChannelStatisticsSerializer(stats)
        return Response(serializer.data)


class ChannelZoneViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing channel zones.
    """
    queryset = ChannelZone.objects.prefetch_related('channels')
    serializer_class = ChannelZoneSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['name', 'description', 'country', 'region']
    filterset_fields = ['country', 'is_active']
    ordering_fields = ['name', 'country', 'created_at']
    ordering = ['name']
    
    @action(detail=True, methods=['get'])
    def channels(self, request, pk=None):
        """
        Get all channels in this zone.
        """
        zone = self.get_object()
        channels = zone.channels.all()
        
        serializer = ChannelListSerializer(channels, many=True)
        return Response(serializer.data)


class ChannelCodecViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing channel codecs.
    """
    queryset = ChannelCodec.objects.all()
    serializer_class = ChannelCodecSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['name', 'description', 'codec_type']
    filterset_fields = ['codec_type', 'is_active']
    ordering_fields = ['name', 'codec_type', 'created_at']
    ordering = ['name']


class ChannelZoneRelationViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing channel-zone relations.
    """
    queryset = ChannelZoneRelation.objects.select_related('channel', 'zone')
    serializer_class = ChannelZoneRelationSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = ['channel', 'zone', 'is_active']
    ordering_fields = ['priority', 'created_at']
    ordering = ['priority']


class EPGProgramViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing EPG programs.
    """
    queryset = EPGProgram.objects.select_related('channel')
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['title', 'description', 'genre']
    filterset_fields = ['channel', 'category', 'genre', 'rating', 'language']
    ordering_fields = ['start_time', 'end_time', 'title']
    ordering = ['start_time']
    
    def get_serializer_class(self):
        """
        Return appropriate serializer class based on action.
        """
        if self.action == 'list':
            return EPGProgramListSerializer
        return EPGProgramDetailSerializer
    
    def get_queryset(self):
        """
        Filter queryset based on query parameters.
        """
        queryset = super().get_queryset()
        
        # Filter by date range
        start_date = self.request.query_params.get('start_date', None)
        end_date = self.request.query_params.get('end_date', None)
        
        if start_date:
            queryset = queryset.filter(start_time__gte=start_date)
        if end_date:
            queryset = queryset.filter(end_time__lte=end_date)
        
        # Filter by current/upcoming programs
        show_current = self.request.query_params.get('current', None)
        if show_current:
            now = timezone.now()
            queryset = queryset.filter(
                start_time__lte=now,
                end_time__gte=now
            )
        
        return queryset


class JingleViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing jingles.
    """
    queryset = Jingle.objects.select_related('channel')
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['name', 'description']
    filterset_fields = ['channel', 'jingle_type', 'is_active']
    ordering_fields = ['name', 'created_at', 'play_count']
    ordering = ['name']
    parser_classes = [MultiPartParser, FormParser, JSONParser]
    
    def get_serializer_class(self):
        """
        Return appropriate serializer class based on action.
        """
        if self.action == 'list':
            return JingleListSerializer
        return JingleDetailSerializer
    
    @action(detail=True, methods=['post'])
    def generate_fingerprint(self, request, pk=None):
        """
        Generate audio fingerprint for a jingle.
        """
        jingle = self.get_object()
        
        # Trigger async fingerprint generation
        task = generate_jingle_fingerprint.delay(jingle.id)
        
        return Response({
            'message': 'Fingerprint generation initiated',
            'task_id': task.id,
            'jingle_id': jingle.id
        })
    
    @action(detail=True, methods=['post'])
    def play(self, request, pk=None):
        """
        Record a play event for a jingle.
        """
        jingle = self.get_object()
        
        # Update play count and last played
        jingle.play_count += 1
        jingle.last_played = timezone.now()
        jingle.save(update_fields=['play_count', 'last_played'])
        
        return Response({
            'message': 'Play recorded',
            'play_count': jingle.play_count,
            'last_played': jingle.last_played
        })


class JingleDetectionViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing jingle detections.
    """
    queryset = JingleDetection.objects.select_related('jingle', 'jingle__channel')
    serializer_class = JingleDetectionSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = ['jingle', 'jingle__channel', 'confidence_score']
    ordering_fields = ['detected_at', 'confidence_score']
    ordering = ['-detected_at']


class ChannelScheduleViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing channel schedules.
    """
    queryset = ChannelSchedule.objects.select_related('channel')
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['title', 'description']
    filterset_fields = ['channel', 'schedule_type', 'is_active']
    ordering_fields = ['start_time', 'end_time', 'priority']
    ordering = ['start_time']
    
    def get_serializer_class(self):
        """
        Return appropriate serializer class based on action.
        """
        if self.action == 'list':
            return ChannelScheduleListSerializer
        return ChannelScheduleDetailSerializer


# ============================================================================
# VPN Configuration ViewSets
# ============================================================================

class IPSecConfigurationViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing IPSec VPN configurations.
    """
    queryset = IPSecConfiguration.objects.all()
    serializer_class = IPSecConfigurationSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination


class OpenVPNConfigurationViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing OpenVPN configurations.
    """
    queryset = OpenVPNConfiguration.objects.all()
    serializer_class = OpenVPNConfigurationSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination


class WireGuardConfigurationViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing WireGuard VPN configurations.
    """
    queryset = WireGuardConfiguration.objects.all()
    serializer_class = WireGuardConfigurationSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination


# ============================================================================
# Custom API Views
# ============================================================================

class ChannelHealthCheckAPIView(APIView):
    """
    API view for channel health checks.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request, pk):
        """
        Trigger health check for a specific channel.
        """
        try:
            channel = Channel.objects.get(pk=pk)
        except Channel.DoesNotExist:
            return Response(
                {'error': 'Channel not found'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        # Trigger async health check
        task = perform_channel_health_check.delay(channel.id)
        
        return Response({
            'message': 'Health check initiated',
            'task_id': task.id,
            'channel_id': channel.id
        })


class ChannelStatisticsAPIView(APIView):
    """
    API view for channel statistics.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request, pk):
        """
        Get detailed statistics for a channel.
        """
        try:
            channel = Channel.objects.get(pk=pk)
        except Channel.DoesNotExist:
            return Response(
                {'error': 'Channel not found'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        # Check cache first
        cache_key = f'channel_stats_{channel.id}'
        stats = cache.get(cache_key)
        
        if not stats:
            stats = {
                'total_programs': channel.programs.count(),
                'total_jingles': channel.jingles.count(),
                'total_zones': channel.zones.count(),
                'health_status': channel.health_status,
                'last_health_check': channel.last_health_check,
                'uptime_percentage': getattr(channel, 'uptime_percentage', None),
                'viewer_count': getattr(channel, 'viewer_count', 0),
            }
            
            # Cache for 5 minutes
            cache.set(cache_key, stats, 300)
        
        return Response(stats)


class BulkChannelActionAPIView(APIView):
    """
    API view for bulk channel actions.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request):
        """
        Perform bulk actions on channels.
        """
        serializer = BulkChannelActionSerializer(data=request.data)
        if serializer.is_valid():
            action = serializer.validated_data['action']
            channel_ids = serializer.validated_data['channel_ids']
            
            channels = Channel.objects.filter(id__in=channel_ids)
            
            if action == 'activate':
                channels.update(status='active')
            elif action == 'deactivate':
                channels.update(status='inactive')
            elif action == 'health_check':
                for channel in channels:
                    perform_channel_health_check.delay(channel.id)
            
            return Response({
                'message': f'Bulk action "{action}" applied to {channels.count()} channels'
            })
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ChannelImportAPIView(APIView):
    """
    API view for importing channels.
    """
    permission_classes = [permissions.IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]
    
    def post(self, request):
        """
        Import channels from CSV file.
        """
        serializer = ChannelImportSerializer(data=request.data)
        if serializer.is_valid():
            file = serializer.validated_data['file']
            
            # Process CSV file
            try:
                decoded_file = file.read().decode('utf-8')
                io_string = io.StringIO(decoded_file)
                reader = csv.DictReader(io_string)
                
                created_count = 0
                errors = []
                
                for row in reader:
                    try:
                        # Create channel from CSV row
                        channel_data = {
                            'name': row.get('name'),
                            'channel_number': row.get('channel_number'),
                            'category': row.get('category', 'entertainment'),
                            'status': row.get('status', 'active'),
                            'stream_url': row.get('stream_url'),
                            'language': row.get('language', 'en'),
                            'country': row.get('country', 'US'),
                        }
                        
                        # Get or create codec
                        codec_name = row.get('codec')
                        if codec_name:
                            codec, _ = ChannelCodec.objects.get_or_create(
                                name=codec_name,
                                defaults={'codec_type': 'h264', 'is_active': True}
                            )
                            channel_data['codec'] = codec
                        
                        channel = Channel.objects.create(**channel_data)
                        created_count += 1
                        
                    except Exception as e:
                        errors.append(f"Row {reader.line_num}: {str(e)}")
                
                return Response({
                    'message': f'Import completed. {created_count} channels created.',
                    'created_count': created_count,
                    'errors': errors
                })
                
            except Exception as e:
                return Response(
                    {'error': f'Failed to process file: {str(e)}'},
                    status=status.HTTP_400_BAD_REQUEST
                )
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ChannelExportAPIView(APIView):
    """
    API view for exporting channels.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Export channels to CSV file.
        """
        channels = Channel.objects.select_related('codec').all()
        
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="channels.csv"'
        
        writer = csv.writer(response)
        writer.writerow([
            'name', 'channel_number', 'category', 'status',
            'stream_url', 'language', 'country', 'codec',
            'is_hd', 'is_encrypted', 'created_at'
        ])
        
        for channel in channels:
            writer.writerow([
                channel.name,
                channel.channel_number,
                channel.category,
                channel.status,
                channel.stream_url,
                channel.language,
                channel.country,
                channel.codec.name if channel.codec else '',
                channel.is_hd,
                channel.is_encrypted,
                channel.created_at.strftime('%Y-%m-%d %H:%M:%S')
            ])
        
        return response


# ============================================================================
# Additional API Views
# ============================================================================

class ZoneChannelsAPIView(APIView):
    """
    API view for getting channels in a specific zone.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request, pk):
        """
        Get all channels in a specific zone.
        """
        try:
            zone = ChannelZone.objects.get(pk=pk)
        except ChannelZone.DoesNotExist:
            return Response(
                {'error': 'Zone not found'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        channels = zone.channels.all()
        serializer = ChannelListSerializer(channels, many=True)
        return Response(serializer.data)


class ZoneStatisticsAPIView(APIView):
    """
    API view for zone statistics.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request, pk):
        """
        Get statistics for a specific zone.
        """
        try:
            zone = ChannelZone.objects.get(pk=pk)
        except ChannelZone.DoesNotExist:
            return Response(
                {'error': 'Zone not found'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        stats = {
            'total_channels': zone.channels.count(),
            'active_channels': zone.channels.filter(status='active').count(),
            'hd_channels': zone.channels.filter(is_hd=True).count(),
            'encrypted_channels': zone.channels.filter(is_encrypted=True).count(),
        }
        
        return Response(stats)


class EPGScheduleAPIView(APIView):
    """
    API view for EPG schedule operations.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Get EPG schedule for specified date range.
        """
        start_date = request.query_params.get('start_date')
        end_date = request.query_params.get('end_date')
        channel_id = request.query_params.get('channel')
        
        queryset = EPGProgram.objects.select_related('channel')
        
        if start_date:
            queryset = queryset.filter(start_time__gte=start_date)
        if end_date:
            queryset = queryset.filter(end_time__lte=end_date)
        if channel_id:
            queryset = queryset.filter(channel_id=channel_id)
        
        queryset = queryset.order_by('start_time')
        
        serializer = EPGProgramListSerializer(queryset, many=True)
        return Response(serializer.data)


class EPGImportAPIView(APIView):
    """
    API view for importing EPG data.
    """
    permission_classes = [permissions.IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]
    
    def post(self, request):
        """
        Import EPG data from XML or JSON file.
        """
        # Implementation would depend on EPG data format
        return Response({'message': 'EPG import functionality to be implemented'})


class EPGExportAPIView(APIView):
    """
    API view for exporting EPG data.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Export EPG data to XML or JSON format.
        """
        # Implementation would depend on required export format
        return Response({'message': 'EPG export functionality to be implemented'})


class JingleFingerprintAPIView(APIView):
    """
    API view for jingle fingerprint operations.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request, pk):
        """
        Generate fingerprint for a jingle.
        """
        try:
            jingle = Jingle.objects.get(pk=pk)
        except Jingle.DoesNotExist:
            return Response(
                {'error': 'Jingle not found'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        # Trigger async fingerprint generation
        task = generate_jingle_fingerprint.delay(jingle.id)
        
        return Response({
            'message': 'Fingerprint generation initiated',
            'task_id': task.id,
            'jingle_id': jingle.id
        })


class JinglePlayAPIView(APIView):
    """
    API view for jingle play operations.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request, pk):
        """
        Record a play event for a jingle.
        """
        try:
            jingle = Jingle.objects.get(pk=pk)
        except Jingle.DoesNotExist:
            return Response(
                {'error': 'Jingle not found'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        # Update play count and last played
        jingle.play_count += 1
        jingle.last_played = timezone.now()
        jingle.save(update_fields=['play_count', 'last_played'])
        
        return Response({
            'message': 'Play recorded',
            'play_count': jingle.play_count,
            'last_played': jingle.last_played
        })


class JingleDetectionAPIView(APIView):
    """
    API view for jingle detection operations.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request):
        """
        Process jingle detection from audio stream.
        """
        # Implementation would depend on audio processing requirements
        return Response({'message': 'Jingle detection functionality to be implemented'})


# ============================================================================
# Search API Views
# ============================================================================

class ChannelSearchAPIView(APIView):
    """
    API view for channel search.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Search channels by various criteria.
        """
        query = request.query_params.get('q', '')
        
        if not query:
            return Response({'results': []})
        
        channels = Channel.objects.filter(
            Q(name__icontains=query) |
            Q(description__icontains=query) |
            Q(channel_number__icontains=query)
        ).select_related('codec')[:20]
        
        serializer = ChannelListSerializer(channels, many=True)
        return Response({'results': serializer.data})


class EPGSearchAPIView(APIView):
    """
    API view for EPG search.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Search EPG programs by various criteria.
        """
        query = request.query_params.get('q', '')
        
        if not query:
            return Response({'results': []})
        
        programs = EPGProgram.objects.filter(
            Q(title__icontains=query) |
            Q(description__icontains=query) |
            Q(genre__icontains=query)
        ).select_related('channel')[:20]
        
        serializer = EPGProgramListSerializer(programs, many=True)
        return Response({'results': serializer.data})


class JingleSearchAPIView(APIView):
    """
    API view for jingle search.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Search jingles by various criteria.
        """
        query = request.query_params.get('q', '')
        
        if not query:
            return Response({'results': []})
        
        jingles = Jingle.objects.filter(
            Q(name__icontains=query) |
            Q(description__icontains=query)
        ).select_related('channel')[:20]
        
        serializer = JingleListSerializer(jingles, many=True)
        return Response({'results': serializer.data})


# ============================================================================
# Analytics API Views
# ============================================================================

class ChannelPerformanceAPIView(APIView):
    """
    API view for channel performance analytics.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Get channel performance metrics.
        """
        # Implementation would depend on analytics requirements
        return Response({'message': 'Channel performance analytics to be implemented'})


class ZoneUsageAPIView(APIView):
    """
    API view for zone usage analytics.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Get zone usage metrics.
        """
        # Implementation would depend on analytics requirements
        return Response({'message': 'Zone usage analytics to be implemented'})


class JingleUsageAPIView(APIView):
    """
    API view for jingle usage analytics.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Get jingle usage metrics.
        """
        # Implementation would depend on analytics requirements
        return Response({'message': 'Jingle usage analytics to be implemented'})


# ============================================================================
# Health Monitoring API Views
# ============================================================================

class ChannelsHealthAPIView(APIView):
    """
    API view for channels health monitoring.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Get health status of all channels.
        """
        channels = Channel.objects.values(
            'id', 'name', 'health_status', 'last_health_check'
        )
        
        health_summary = {
            'total_channels': channels.count(),
            'healthy_channels': channels.filter(health_status='healthy').count(),
            'unhealthy_channels': channels.filter(health_status='unhealthy').count(),
            'unknown_channels': channels.filter(health_status__isnull=True).count(),
            'channels': list(channels)
        }
        
        return Response(health_summary)


class ZonesHealthAPIView(APIView):
    """
    API view for zones health monitoring.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Get health status of all zones.
        """
        zones = ChannelZone.objects.annotate(
            total_channels=Count('channels'),
            healthy_channels=Count('channels', filter=Q(channels__health_status='healthy'))
        ).values(
            'id', 'name', 'total_channels', 'healthy_channels'
        )
        
        return Response({'zones': list(zones)})


class SystemHealthAPIView(APIView):
    """
    API view for overall system health monitoring.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Get overall system health metrics.
        """
        system_health = {
            'total_channels': Channel.objects.count(),
            'active_channels': Channel.objects.filter(status='active').count(),
            'healthy_channels': Channel.objects.filter(health_status='healthy').count(),
            'total_zones': ChannelZone.objects.count(),
            'active_zones': ChannelZone.objects.filter(is_active=True).count(),
            'total_programs': EPGProgram.objects.count(),
            'total_jingles': Jingle.objects.count(),
            'system_status': 'operational',  # This could be calculated based on various metrics
            'last_updated': timezone.now()
        }
        
        return Response(system_health)


# ============================================================================
# Schedule API Views
# ============================================================================

class UpcomingSchedulesAPIView(APIView):
    """
    API view for upcoming schedules.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Get upcoming schedules.
        """
        now = timezone.now()
        hours = int(request.query_params.get('hours', 24))
        end_time = now + timedelta(hours=hours)
        
        schedules = ChannelSchedule.objects.filter(
            start_time__gte=now,
            start_time__lte=end_time,
            is_active=True
        ).select_related('channel').order_by('start_time')
        
        serializer = ChannelScheduleListSerializer(schedules, many=True)
        return Response(serializer.data)


class ScheduleConflictsAPIView(APIView):
    """
    API view for schedule conflicts detection.
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        """
        Detect schedule conflicts.
        """
        # Implementation would depend on conflict detection logic
        return Response({'message': 'Schedule conflicts detection to be implemented'})