"""
Django Admin Configuration for Jingles Application

This module configures the Django admin interface for jingle detection,
ad break management, and related functionality.
"""

from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from  apps.jingles.models import (
    JingleTemplate, JingleDetection, AdBreak, DetectionStatistics
)


@admin.register(JingleTemplate)
class JingleTemplateAdmin(admin.ModelAdmin):
    """
    Admin interface for JingleTemplate model.
    
    Provides management of jingle reference templates including
    image upload, similarity threshold configuration, and status monitoring.
    """
    
    # List display configuration
    list_display = [
        'name', 'category', 'is_active', 'similarity_threshold',
        'get_detection_count', 'image_status', 'created_by', 'created_at'
    ]
    
    # List filtering options
    list_filter = [
        'category', 'is_active', 'created_at', 'created_by'
    ]
    
    # Search functionality
    search_fields = [
        'name', 'slug', 'description'
    ]
    
    # Field organization
    fieldsets = (
        ('Template Information', {
            'fields': ('name', 'slug', 'description', 'category')
        }),
        ('Detection Configuration', {
            'fields': ('image_path', 'similarity_threshold', 'is_active')
        }),
        ('Metadata', {
            'fields': ('created_by',),
            'classes': ('collapse',)
        })
    )
    
    # Prepopulated fields
    prepopulated_fields = {'slug': ('name',)}
    
    # Read-only fields
    readonly_fields = ['created_at', 'updated_at']
    
    # Ordering
    ordering = ['category', 'name']
    
    def get_detection_count(self, obj):
        """Get the total number of detections for this template."""
        count = obj.detections.count()
        confirmed_count = obj.detections.filter(is_confirmed=True).count()
        
        if count > 0:
            percentage = (confirmed_count / count) * 100
            color = 'green' if percentage > 80 else 'orange' if percentage > 50 else 'red'
            
            return format_html(
                '<span style="color: {};">{} total<br/>({} confirmed)</span>',
                color,
                count,
                confirmed_count
            )
        return format_html('<span style="color: gray;">No detections</span>')
    
    get_detection_count.short_description = 'Detections'
    
    def image_status(self, obj):
        """Check if the template image file exists."""
        if obj.image_exists():
            return format_html(
                '<span style="color: green;">✓ Available</span>'
            )
        else:
            return format_html(
                '<span style="color: red;">✗ Missing</span>'
            )
    
    image_status.short_description = 'Image File'
    
    def get_queryset(self, request):
        """Optimize queryset with prefetch_related."""
        return super().get_queryset(request).select_related('created_by')


class JingleDetectionInline(admin.TabularInline):
    """
    Inline admin for jingle detections within ad breaks.
    """
    
    model = JingleDetection
    extra = 0
    readonly_fields = [
        'template', 'confidence_score', 'detection_time', 'is_confirmed'
    ]
    fields = ['template', 'confidence_score', 'detection_time', 'is_confirmed']
    
    def has_add_permission(self, request, obj=None):
        """Disable adding detections through admin."""
        return False


@admin.register(JingleDetection)
class JingleDetectionAdmin(admin.ModelAdmin):
    """
    Admin interface for JingleDetection model.
    
    Provides detailed management of individual jingle detections
    including confidence scores, frame analysis, and confirmation status.
    """
    
    # List display configuration
    list_display = [
        'get_detection_info', 'template', 'session', 'confidence_score',
        'is_confirmed', 'detection_time'
    ]
    
    # List filtering options
    list_filter = [
        'template', 'is_confirmed', 'detection_time', 'session__channel'
    ]
    
    # Search functionality
    search_fields = [
        'template__name', 'session__channel__name'
    ]
    
    # Field organization
    fieldsets = (
        ('Detection Information', {
            'fields': ('session', 'segment', 'template')
        }),
        ('Detection Results', {
            'fields': ('confidence_score', 'frame_timestamp', 'is_confirmed')
        }),
        ('Frame Data', {
            'fields': ('frame_path', 'detection_time')
        }),
        ('Additional Metadata', {
            'fields': ('metadata',),
            'classes': ('collapse',)
        })
    )
    
    # Read-only fields
    readonly_fields = [
        'detection_time', 'created_at', 'updated_at'
    ]
    
    # Ordering
    ordering = ['-detection_time']
    
    def get_detection_info(self, obj):
        """Get formatted detection information."""
        confidence_color = 'green' if obj.confidence_score > 0.8 else 'orange' if obj.confidence_score > 0.5 else 'red'
        confirmation_text = '✓ Confirmed' if obj.is_confirmed else '? Unconfirmed'
        confirmation_color = 'green' if obj.is_confirmed else 'gray'
        
        return format_html(
            '<strong>{:.3f}</strong><br/>'
            '<span style="color: {};">{}</span>',
            obj.confidence_score,
            confirmation_color,
            confirmation_text
        )
    
    get_detection_info.short_description = 'Detection'
    get_detection_info.admin_order_field = 'confidence_score'
    
    def get_queryset(self, request):
        """Optimize queryset with select_related."""
        return super().get_queryset(request).select_related(
            'template', 'session__channel', 'segment'
        )


@admin.register(AdBreak)
class AdBreakAdmin(admin.ModelAdmin):
    """
    Admin interface for AdBreak model.
    
    Provides comprehensive management of advertisement breaks including
    timing analysis, external API integration, and status tracking.
    """
    
    # List display configuration
    list_display = [
        'get_adbreak_info', 'channel_name', 'region', 'start_time',
        'duration_display', 'status', 'is_sent_to_api'
    ]
    
    # List filtering options
    list_filter = [
        'status', 'region', 'is_sent_to_api', 'start_time', 'session__channel'
    ]
    
    # Search functionality
    search_fields = [
        'channel_name', 'session__channel__name'
    ]
    
    # Field organization
    fieldsets = (
        ('Ad Break Information', {
            'fields': ('session', 'channel_name', 'region', 'status')
        }),
        ('Timing', {
            'fields': ('start_time', 'end_time', 'duration_seconds')
        }),
        ('Detection References', {
            'fields': ('start_detection', 'end_detection')
        }),
        ('External Integration', {
            'fields': ('is_sent_to_api', 'api_response')
        }),
        ('Notes', {
            'fields': ('notes',),
            'classes': ('collapse',)
        })
    )
    
    # Read-only fields
    readonly_fields = [
        'created_at', 'updated_at', 'duration_seconds'
    ]
    
    # Inline models
    inlines = []  # JingleDetectionInline would go here if needed
    
    # Ordering
    ordering = ['-start_time']
    
    def get_adbreak_info(self, obj):
        """Get formatted ad break information."""
        status_color = {
            'active': 'orange',
            'completed': 'green',
            'failed': 'red',
            'cancelled': 'gray',
        }.get(obj.status, 'black')
        
        api_status = '📤 Sent' if obj.is_sent_to_api else '📥 Pending'
        api_color = 'green' if obj.is_sent_to_api else 'orange'
        
        return format_html(
            '<span style="color: {};">{}</span><br/>'
            '<small style="color: {};">{}</small>',
            status_color,
            obj.status.title(),
            api_color,
            api_status
        )
    
    get_adbreak_info.short_description = 'Status'
    get_adbreak_info.admin_order_field = 'status'
    
    def duration_display(self, obj):
        """Display ad break duration in a readable format."""
        if obj.duration_seconds:
            minutes = obj.duration_seconds // 60
            seconds = obj.duration_seconds % 60
            
            if minutes > 0:
                return f"{minutes}m {seconds}s"
            else:
                return f"{seconds}s"
        elif obj.is_complete():
            # Calculate duration if not stored
            duration = obj.calculate_duration()
            if duration:
                minutes = duration // 60
                seconds = duration % 60
                return f"{minutes}m {seconds}s (calc)"
        
        return "-"
    
    duration_display.short_description = 'Duration'
    duration_display.admin_order_field = 'duration_seconds'
    
    def get_queryset(self, request):
        """Optimize queryset with select_related."""
        return super().get_queryset(request).select_related(
            'session__channel', 'start_detection__template', 'end_detection__template'
        )


@admin.register(DetectionStatistics)
class DetectionStatisticsAdmin(admin.ModelAdmin):
    """
    Admin interface for DetectionStatistics model.
    
    Provides analysis and reporting of jingle detection performance
    including accuracy metrics and trend analysis.
    """
    
    # List display configuration
    list_display = [
        'get_stats_info', 'template', 'session', 'total_detections',
        'accuracy_rate_display', 'avg_confidence', 'last_detection'
    ]
    
    # List filtering options
    list_filter = [
        'template', 'session__channel', 'last_detection'
    ]
    
    # Search functionality
    search_fields = [
        'template__name', 'session__channel__name'
    ]
    
    # Field organization
    fieldsets = (
        ('Statistics Overview', {
            'fields': ('session', 'template')
        }),
        ('Detection Counts', {
            'fields': ('total_detections', 'confirmed_detections', 'false_positives')
        }),
        ('Confidence Metrics', {
            'fields': ('avg_confidence', 'min_confidence', 'max_confidence')
        }),
        ('Performance Metrics', {
            'fields': ('detection_rate', 'last_detection')
        })
    )
    
    # Read-only fields
    readonly_fields = [
        'created_at', 'updated_at', 'total_detections', 'confirmed_detections',
        'false_positives', 'avg_confidence', 'min_confidence', 'max_confidence',
        'detection_rate', 'last_detection'
    ]
    
    # Ordering
    ordering = ['-last_detection']
    
    def get_stats_info(self, obj):
        """Get formatted statistics information."""
        accuracy = obj.accuracy_rate()
        accuracy_color = 'green' if accuracy > 80 else 'orange' if accuracy > 50 else 'red'
        
        return format_html(
            '<strong>{:.1f}%</strong><br/>'
            '<span style="color: {};">Accuracy</span>',
            accuracy,
            accuracy_color
        )
    
    get_stats_info.short_description = 'Performance'
    
    def accuracy_rate_display(self, obj):
        """Display accuracy rate with color coding."""
        rate = obj.accuracy_rate()
        color = 'green' if rate > 80 else 'orange' if rate > 50 else 'red'
        
        return format_html(
            '<span style="color: {};">{:.1f}%</span>',
            color,
            rate
        )
    
    accuracy_rate_display.short_description = 'Accuracy'
    accuracy_rate_display.admin_order_field = 'confirmed_detections'
    
    def get_queryset(self, request):
        """Optimize queryset with select_related."""
        return super().get_queryset(request).select_related(
            'template', 'session__channel'
        )
    
    def has_add_permission(self, request):
        """Disable manual creation of statistics."""
        return False
