# -*- coding: utf-8 -*-
"""
Channel Management Django Admin Configuration

This module configures Django admin interfaces for channel management models
including channels, zones, codecs, EPG programs, jingles, and schedules.
"""

from django.contrib import admin
from django.utils.html import format_html
from django.utils import timezone
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.db.models import Count, Q
from django.contrib.admin import SimpleListFilter
from django.utils.translation import gettext_lazy as _

from .models import (
    Channel, ChannelZone, ChannelCodec, ChannelZoneRelation,
    EPGProgram, Jingle, JingleDetection, ChannelSchedule,
    VPNConfiguration, IPSecConfiguration, OpenVPNConfiguration, WireGuardConfiguration
)
from .forms import ChannelForm, ChannelZoneForm, ChannelCodecForm, EPGProgramForm, JingleForm


# ============================================================================
# Custom Filters
# ============================================================================

class HealthStatusFilter(SimpleListFilter):
    """
    Custom filter for channel health status.
    """
    title = _('Health Status')
    parameter_name = 'health_status'
    
    def lookups(self, request, model_admin):
        return (
            ('healthy', _('Healthy')),
            ('warning', _('Warning')),
            ('unhealthy', _('Unhealthy')),
            ('unknown', _('Unknown')),
        )
    
    def queryset(self, request, queryset):
        if self.value() == 'healthy':
            return queryset.filter(health_status='healthy')
        elif self.value() == 'warning':
            return queryset.filter(health_status='warning')
        elif self.value() == 'unhealthy':
            return queryset.filter(health_status='unhealthy')
        elif self.value() == 'unknown':
            return queryset.filter(health_status__isnull=True)
        return queryset


class RecentActivityFilter(SimpleListFilter):
    """
    Custom filter for recent activity.
    """
    title = _('Recent Activity')
    parameter_name = 'recent_activity'
    
    def lookups(self, request, model_admin):
        return (
            ('today', _('Today')),
            ('week', _('This Week')),
            ('month', _('This Month')),
        )
    
    def queryset(self, request, queryset):
        now = timezone.now()
        if self.value() == 'today':
            return queryset.filter(updated_at__date=now.date())
        elif self.value() == 'week':
            week_ago = now - timezone.timedelta(days=7)
            return queryset.filter(updated_at__gte=week_ago)
        elif self.value() == 'month':
            month_ago = now - timezone.timedelta(days=30)
            return queryset.filter(updated_at__gte=month_ago)
        return queryset


# ============================================================================
# Inline Admin Classes
# ============================================================================

class ChannelZoneRelationInline(admin.TabularInline):
    """
    Inline admin for channel-zone relations.
    """
    model = ChannelZoneRelation
    extra = 0
    fields = ['zone', 'priority', 'is_active', 'zone_specific_url', 'vpn_type']
    readonly_fields = ['created_at', 'updated_at']


class EPGProgramInline(admin.TabularInline):
    """
    Inline admin for EPG programs.
    """
    model = EPGProgram
    extra = 0
    fields = ['title', 'start_time', 'end_time', 'category', 'rating']
    readonly_fields = ['created_at', 'updated_at']
    ordering = ['start_time']


class JingleInline(admin.TabularInline):
    """
    Inline admin for jingles.
    """
    model = Jingle
    extra = 0
    fields = ['name', 'jingle_type', 'duration', 'is_active']
    readonly_fields = ['created_at', 'updated_at']


class JingleDetectionInline(admin.TabularInline):
    """
    Inline admin for jingle detections.
    """
    model = JingleDetection
    extra = 0
    fields = ['channel', 'detected_at', 'confidence_score', 'status']
    readonly_fields = ['detected_at', 'created_at']
    ordering = ['-detected_at']


# ============================================================================
# Main Admin Classes
# ============================================================================

@admin.register(Channel)
class ChannelAdmin(admin.ModelAdmin):
    """
    Admin interface for Channel model.
    """
    form = ChannelForm
    list_display = [
        'name', 'channel_number', 'category', 'status', 'health_status_display',
        'is_hd', 'is_encrypted', 'zone_count', 'last_health_check', 'created_at'
    ]
    list_filter = [
        'status', 'category', 'is_hd', 'is_encrypted', 'language', 'country',
        HealthStatusFilter, RecentActivityFilter, 'created_at'
    ]
    search_fields = ['name', 'description', 'channel_number', 'stream_url']
    readonly_fields = [
        'id', 'health_status', 'last_health_check', 'created_at', 'updated_at',
        'logo_preview', 'stream_status'
    ]
    fieldsets = (
        (_('Basic Information'), {
            'fields': ('name', 'description', 'channel_number', 'category', 'language', 'country')
        }),
        (_('Technical Settings'), {
            'fields': ('codec', 'stream_url', 'backup_stream_url', 'timezone')
        }),
        (_('Media'), {
            'fields': ('logo', 'logo_preview')
        }),
        (_('Security'), {
            'fields': ('is_encrypted', 'encryption_key')
        }),
        (_('Status & Health'), {
            'fields': ('status', 'health_status', 'last_health_check', 'stream_status')
        }),
        (_('Features'), {
            'fields': ('is_hd', 'metadata')
        }),
        (_('Timestamps'), {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    inlines = [ChannelZoneRelationInline, EPGProgramInline, JingleInline]
    actions = ['activate_channels', 'deactivate_channels', 'perform_health_check']
    
    def health_status_display(self, obj):
        """
        Display health status with color coding.
        """
        if obj.health_status == 'healthy':
            color = 'green'
            icon = '✓'
        elif obj.health_status == 'warning':
            color = 'orange'
            icon = '⚠'
        elif obj.health_status == 'unhealthy':
            color = 'red'
            icon = '✗'
        else:
            color = 'gray'
            icon = '?'
        
        return format_html(
            '<span style="color: {};"><strong>{} {}</strong></span>',
            color, icon, obj.health_status or 'Unknown'
        )
    health_status_display.short_description = _('Health Status')
    
    def logo_preview(self, obj):
        """
        Display logo preview in admin.
        """
        if obj.logo:
            return format_html(
                '<img src="{}" style="max-height: 100px; max-width: 200px;"/>',
                obj.logo.url
            )
        return _('No logo')
    logo_preview.short_description = _('Logo Preview')
    
    def stream_status(self, obj):
        """
        Display stream status.
        """
        # This would integrate with actual stream checking
        return format_html(
            '<span style="color: green;">● Online</span>'
        )
    stream_status.short_description = _('Stream Status')
    
    def zone_count(self, obj):
        """
        Display number of zones for this channel.
        """
        return obj.zones.count()
    zone_count.short_description = _('Zones')
    
    def activate_channels(self, request, queryset):
        """
        Bulk activate channels.
        """
        updated = queryset.update(status='active')
        self.message_user(request, f'{updated} channels were activated.')
    activate_channels.short_description = _('Activate selected channels')
    
    def deactivate_channels(self, request, queryset):
        """
        Bulk deactivate channels.
        """
        updated = queryset.update(status='inactive')
        self.message_user(request, f'{updated} channels were deactivated.')
    deactivate_channels.short_description = _('Deactivate selected channels')
    
    def perform_health_check(self, request, queryset):
        """
        Perform health check on selected channels.
        """
        from .tasks import perform_channel_health_check
        
        count = 0
        for channel in queryset:
            perform_channel_health_check.delay(channel.id)
            count += 1
        
        self.message_user(request, f'Health checks scheduled for {count} channels.')
    perform_health_check.short_description = _('Perform health check')


@admin.register(ChannelZone)
class ChannelZoneAdmin(admin.ModelAdmin):
    """
    Admin interface for ChannelZone model.
    """
    form = ChannelZoneForm
    list_display = ['name', 'country', 'region', 'timezone', 'channel_count', 'is_active', 'created_at']
    list_filter = ['country', 'is_active', 'timezone', 'created_at']
    search_fields = ['name', 'description', 'country', 'region']
    readonly_fields = ['id', 'created_at', 'updated_at']
    
    def channel_count(self, obj):
        """
        Display number of channels in this zone.
        """
        return obj.channels.count()
    channel_count.short_description = _('Channels')


@admin.register(ChannelCodec)
class ChannelCodecAdmin(admin.ModelAdmin):
    """
    Admin interface for ChannelCodec model.
    """
    form = ChannelCodecForm
    list_display = ['name', 'codec_type', 'channel_count', 'is_active', 'created_at']
    list_filter = ['codec_type', 'is_active', 'created_at']
    search_fields = ['name', 'description']
    readonly_fields = ['id', 'created_at', 'updated_at']
    
    def channel_count(self, obj):
        """
        Display number of channels using this codec.
        """
        return obj.channels.count()
    channel_count.short_description = _('Channels')


@admin.register(ChannelZoneRelation)
class ChannelZoneRelationAdmin(admin.ModelAdmin):
    """
    Admin interface for ChannelZoneRelation model.
    """
    list_display = [
        'channel', 'zone', 'priority', 'vpn_type', 'vpn_status_display',
        'is_active', 'created_at'
    ]
    list_filter = ['vpn_type', 'is_active', 'priority', 'created_at']
    search_fields = ['channel__name', 'zone__name']
    readonly_fields = ['id', 'last_vpn_test', 'vpn_status', 'created_at', 'updated_at']
    
    def vpn_status_display(self, obj):
        """
        Display VPN status with color coding.
        """
        if obj.vpn_type == 'none':
            return format_html('<span style="color: gray;">No VPN</span>')
        
        if obj.vpn_status == 'connected':
            color = 'green'
            icon = '●'
        elif obj.vpn_status == 'disconnected':
            color = 'red'
            icon = '●'
        else:
            color = 'orange'
            icon = '●'
        
        return format_html(
            '<span style="color: {};">{} {}</span>',
            color, icon, obj.vpn_status or 'Unknown'
        )
    vpn_status_display.short_description = _('VPN Status')


@admin.register(EPGProgram)
class EPGProgramAdmin(admin.ModelAdmin):
    """
    Admin interface for EPGProgram model.
    """
    form = EPGProgramForm
    list_display = [
        'title', 'channel', 'start_time', 'end_time', 'duration',
        'category', 'rating', 'has_subtitles', 'has_ad_breaks'
    ]
    list_filter = [
        'category', 'rating', 'has_subtitles', 'has_ad_breaks',
        'language', 'country', 'start_time'
    ]
    search_fields = ['title', 'description', 'director', 'cast']
    readonly_fields = ['id', 'created_at', 'updated_at']
    date_hierarchy = 'start_time'
    
    fieldsets = (
        (_('Basic Information'), {
            'fields': ('channel', 'title', 'description', 'category', 'genre')
        }),
        (_('Schedule'), {
            'fields': ('start_time', 'end_time', 'duration')
        }),
        (_('Content Details'), {
            'fields': ('rating', 'language', 'director', 'cast', 'year', 'country')
        }),
        (_('Series Information'), {
            'fields': ('episode_number', 'season_number')
        }),
        (_('Features'), {
            'fields': ('has_subtitles', 'has_ad_breaks', 'ad_break_positions')
        }),
        (_('Metadata'), {
            'fields': ('metadata',),
            'classes': ('collapse',)
        }),
        (_('Timestamps'), {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )


@admin.register(Jingle)
class JingleAdmin(admin.ModelAdmin):
    """
    Admin interface for Jingle model.
    """
    form = JingleForm
    list_display = [
        'name', 'channel', 'jingle_type', 'duration', 'volume_level',
        'play_count', 'is_active', 'created_at'
    ]
    list_filter = ['jingle_type', 'is_active', 'channel', 'created_at']
    search_fields = ['name', 'description', 'channel__name']
    readonly_fields = [
        'id', 'play_count', 'last_played', 'fingerprint', 'fingerprint_generated_at',
        'created_at', 'updated_at', 'audio_preview'
    ]
    inlines = [JingleDetectionInline]
    
    fieldsets = (
        (_('Basic Information'), {
            'fields': ('channel', 'name', 'description', 'jingle_type')
        }),
        (_('Audio File'), {
            'fields': ('file', 'audio_preview')
        }),
        (_('Audio Settings'), {
            'fields': ('duration', 'volume_level', 'fade_in', 'fade_out')
        }),
        (_('Fingerprint'), {
            'fields': ('fingerprint', 'fingerprint_generated_at'),
            'classes': ('collapse',)
        }),
        (_('Usage Statistics'), {
            'fields': ('play_count', 'last_played'),
            'classes': ('collapse',)
        }),
        (_('Status'), {
            'fields': ('is_active',)
        }),
        (_('Metadata'), {
            'fields': ('metadata',),
            'classes': ('collapse',)
        }),
        (_('Timestamps'), {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def audio_preview(self, obj):
        """
        Display audio preview in admin.
        """
        if obj.file:
            return format_html(
                '<audio controls><source src="{}" type="audio/mpeg">Your browser does not support the audio element.</audio>',
                obj.file.url
            )
        return _('No audio file')
    audio_preview.short_description = _('Audio Preview')


@admin.register(JingleDetection)
class JingleDetectionAdmin(admin.ModelAdmin):
    """
    Admin interface for JingleDetection model.
    """
    list_display = [
        'jingle', 'channel', 'detected_at', 'confidence_score',
        'status', 'confidence_display'
    ]
    list_filter = ['status', 'channel', 'detected_at']
    search_fields = ['jingle__name', 'channel__name']
    readonly_fields = ['id', 'detected_at', 'created_at', 'updated_at']
    date_hierarchy = 'detected_at'
    
    def confidence_display(self, obj):
        """
        Display confidence score with color coding.
        """
        score = obj.confidence_score
        if score >= 0.9:
            color = 'green'
        elif score >= 0.7:
            color = 'orange'
        else:
            color = 'red'
        
        return format_html(
            '<span style="color: {};"><strong>{:.1%}</strong></span>',
            color, score
        )
    confidence_display.short_description = _('Confidence')


@admin.register(ChannelSchedule)
class ChannelScheduleAdmin(admin.ModelAdmin):
    """
    Admin interface for ChannelSchedule model.
    """
    list_display = [
        'title', 'channel', 'schedule_type', 'start_time', 'end_time',
        'is_recurring', 'priority', 'is_active'
    ]
    list_filter = [
        'schedule_type', 'is_recurring', 'is_active', 'priority',
        'channel', 'start_time'
    ]
    search_fields = ['title', 'description', 'channel__name']
    readonly_fields = ['id', 'created_at', 'updated_at']
    date_hierarchy = 'start_time'
    
    fieldsets = (
        (_('Basic Information'), {
            'fields': ('channel', 'title', 'description', 'schedule_type')
        }),
        (_('Schedule'), {
            'fields': ('start_time', 'end_time', 'is_recurring', 'recurrence_pattern')
        }),
        (_('Settings'), {
            'fields': ('priority', 'is_active')
        }),
        (_('Metadata'), {
            'fields': ('metadata',),
            'classes': ('collapse',)
        }),
        (_('Timestamps'), {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )


# ============================================================================
# VPN Configuration Admin
# ============================================================================

@admin.register(IPSecConfiguration)
class IPSecConfigurationAdmin(admin.ModelAdmin):
    """
    Admin interface for IPSec VPN configurations.
    """
    list_display = ['name', 'server_address', 'is_active', 'created_at']
    list_filter = ['is_active', 'created_at']
    search_fields = ['name', 'server_address']
    readonly_fields = ['id', 'created_at', 'updated_at']


@admin.register(OpenVPNConfiguration)
class OpenVPNConfigurationAdmin(admin.ModelAdmin):
    """
    Admin interface for OpenVPN configurations.
    """
    list_display = ['name', 'server_address', 'port', 'protocol', 'is_active', 'created_at']
    list_filter = ['protocol', 'is_active', 'created_at']
    search_fields = ['name', 'server_address']
    readonly_fields = ['id', 'created_at', 'updated_at']


@admin.register(WireGuardConfiguration)
class WireGuardConfigurationAdmin(admin.ModelAdmin):
    """
    Admin interface for WireGuard VPN configurations.
    """
    list_display = ['name', 'server_address', 'port', 'is_active', 'created_at']
    list_filter = ['is_active', 'created_at']
    search_fields = ['name', 'server_address']
    readonly_fields = ['id', 'created_at', 'updated_at']


# ============================================================================
# Admin Site Customization
# ============================================================================

# Customize admin site header and title
admin.site.site_header = _('Adtlas Channel Management')
admin.site.site_title = _('Adtlas Admin')
admin.site.index_title = _('Channel Management Dashboard')
