"""
Optimization Models
Phase 4: Linker & Optimizer
"""
from django.db import models
from django.core.validators import MinValueValidator
from igny8_core.auth.models import AccountBaseModel
from igny8_core.business.content.models import Content


class OptimizationTask(AccountBaseModel):
    """
    Optimization Task model for tracking content optimization runs.
    """
    
    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('running', 'Running'),
        ('completed', 'Completed'),
        ('failed', 'Failed'),
    ]
    
    content = models.ForeignKey(
        Content,
        on_delete=models.CASCADE,
        related_name='optimization_tasks',
        help_text="The content being optimized"
    )
    
    # Scores before and after optimization
    scores_before = models.JSONField(default=dict, help_text="Optimization scores before")
    scores_after = models.JSONField(default=dict, help_text="Optimization scores after")
    
    # Content before and after (for comparison)
    html_before = models.TextField(blank=True, help_text="HTML content before optimization")
    html_after = models.TextField(blank=True, help_text="HTML content after optimization")
    
    # Status
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending',
        db_index=True,
        help_text="Optimization task status"
    )
    
    # Credits used
    credits_used = models.IntegerField(default=0, validators=[MinValueValidator(0)], help_text="Credits used for optimization")
    
    # Metadata
    metadata = models.JSONField(default=dict, blank=True, help_text="Additional metadata")
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        app_label = 'optimization'
        db_table = 'igny8_optimization_tasks'
        ordering = ['-created_at']
        verbose_name = 'Optimization Task'
        verbose_name_plural = 'Optimization Tasks'
        indexes = [
            models.Index(fields=['content', 'status']),
            models.Index(fields=['account', 'status']),
            models.Index(fields=['status', 'created_at']),
        ]
    
    def save(self, *args, **kwargs):
        """Automatically set account from content"""
        if self.content:
            self.account = self.content.account
        super().save(*args, **kwargs)
    
    def __str__(self):
        return f"Optimization for {self.content.title or 'Content'} ({self.get_status_display()})"


