from django.db import models
from django.utils import timezone

from apps.channels.models import Channel
from apps.playlists.models import Playlist
from apps.campaigns.models import Campaign, AdSpot


class VastRequest(models.Model):
    """Track VAST ad requests"""
    
    # Request details
    request_id = models.CharField(max_length=255, unique=True)
    channel = models.ForeignKey(Channel, on_delete=models.CASCADE, null=True, blank=True)
    playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True, blank=True)
    
    # Client information
    user_agent = models.TextField(null=True, blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    referrer = models.URLField(null=True, blank=True)
    
    # Request parameters
    width = models.IntegerField(null=True, blank=True)
    height = models.IntegerField(null=True, blank=True)
    duration = models.IntegerField(null=True, blank=True)  # in seconds
    
    # Response details
    selected_adspot = models.ForeignKey(AdSpot, on_delete=models.CASCADE, null=True, blank=True)
    response_status = models.CharField(max_length=50, default='pending')
    response_time_ms = models.IntegerField(null=True, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'vast_requests'
        verbose_name = 'VAST Request'
        verbose_name_plural = 'VAST Requests'
        ordering = ['-created_at']


class VastResponse(models.Model):
    """Store VAST XML responses"""
    
    request = models.OneToOneField(VastRequest, on_delete=models.CASCADE, related_name='response')
    vast_xml = models.TextField()
    adspot = models.ForeignKey(AdSpot, on_delete=models.CASCADE)
    campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE)
    
    # Tracking URLs
    impression_url = models.URLField(null=True, blank=True)
    click_url = models.URLField(null=True, blank=True)
    start_url = models.URLField(null=True, blank=True)
    firstquartile_url = models.URLField(null=True, blank=True)
    midpoint_url = models.URLField(null=True, blank=True)
    thirdquartile_url = models.URLField(null=True, blank=True)
    complete_url = models.URLField(null=True, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'vast_responses'
        verbose_name = 'VAST Response'
        verbose_name_plural = 'VAST Responses'
        ordering = ['-created_at']


class VastTracking(models.Model):
    """Track VAST events (impressions, clicks, quartiles)"""
    
    EVENT_TYPES = [
        ('impression', 'Impression'),
        ('start', 'Start'),
        ('firstQuartile', 'First Quartile'),
        ('midpoint', 'Midpoint'),
        ('thirdQuartile', 'Third Quartile'),
        ('complete', 'Complete'),
        ('click', 'Click'),
        ('pause', 'Pause'),
        ('resume', 'Resume'),
        ('mute', 'Mute'),
        ('unmute', 'Unmute'),
        ('fullscreen', 'Fullscreen'),
        ('exitFullscreen', 'Exit Fullscreen'),
        ('error', 'Error'),
    ]
    
    request = models.ForeignKey(VastRequest, on_delete=models.CASCADE, related_name='tracking_events')
    event_type = models.CharField(max_length=20, choices=EVENT_TYPES)
    
    # Client information at time of event
    user_agent = models.TextField(null=True, blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    
    # Event details
    timestamp = models.DateTimeField(default=timezone.now)
    video_position = models.IntegerField(null=True, blank=True)  # in seconds
    error_code = models.CharField(max_length=10, null=True, blank=True)
    error_message = models.TextField(null=True, blank=True)
    
    # Additional metadata
    metadata = models.JSONField(default=dict, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'vast_tracking'
        verbose_name = 'VAST Tracking Event'
        verbose_name_plural = 'VAST Tracking Events'
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['request', 'event_type']),
            models.Index(fields=['timestamp']),
        ]


class VastTemplate(models.Model):
    """VAST XML templates for different ad types"""
    
    AD_TYPES = [
        ('linear', 'Linear Video Ad'),
        ('nonlinear', 'Non-Linear Ad'),
        ('companion', 'Companion Ad'),
    ]
    
    name = models.CharField(max_length=255)
    ad_type = models.CharField(max_length=20, choices=AD_TYPES)
    template_xml = models.TextField()
    description = models.TextField(null=True, blank=True)
    
    # Template variables that can be replaced
    variables = models.JSONField(default=list, help_text="List of variables that can be replaced in template")
    
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'vast_templates'
        verbose_name = 'VAST Template'
        verbose_name_plural = 'VAST Templates'
        ordering = ['name']


class AdDecisionEngine(models.Model):
    """Configuration for ad decision logic"""
    
    DECISION_TYPES = [
        ('round_robin', 'Round Robin'),
        ('weighted', 'Weighted Random'),
        ('priority', 'Priority Based'),
        ('frequency_cap', 'Frequency Capping'),
        ('daypart', 'Daypart Targeting'),
    ]
    
    name = models.CharField(max_length=255)
    decision_type = models.CharField(max_length=20, choices=DECISION_TYPES)
    configuration = models.JSONField(default=dict)
    
    # Targeting criteria
    channels = models.ManyToManyField(Channel, blank=True)
    campaigns = models.ManyToManyField(Campaign, blank=True)
    
    is_active = models.BooleanField(default=True)
    priority = models.IntegerField(default=0)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'ad_decision_engines'
        verbose_name = 'Ad Decision Engine'
        verbose_name_plural = 'Ad Decision Engines'
        ordering = ['-priority', 'name']