from django.db import models
from django.utils.translation import gettext_lazy as _
from django.core.validators import FileExtensionValidator

from apps.accounts.models import User 
from apps.common.models import BaseModel


from apps.agencies.utils import brand_logo_upload_path




class BrandCategory(models.TextChoices):
    """Brand category choices"""
    TECHNOLOGY = 'technology', _('Technology')
    FASHION = 'fashion', _('Fashion')
    FOOD_BEVERAGE = 'food_beverage', _('Food & Beverage')
    AUTOMOTIVE = 'automotive', _('Automotive')
    HEALTHCARE = 'healthcare', _('Healthcare')
    FINANCE = 'finance', _('Finance')
    ENTERTAINMENT = 'entertainment', _('Entertainment')
    RETAIL = 'retail', _('Retail')
    TRAVEL = 'travel', _('Travel')
    EDUCATION = 'education', _('Education')
    REAL_ESTATE = 'real_estate', _('Real Estate')
    OTHER = 'other', _('Other')


class BrandStatus(models.TextChoices):
    """Brand status choices"""
    ACTIVE = 'active', _('Active')
    INACTIVE = 'inactive', _('Inactive')
    PENDING = 'pending', _('Pending')
    SUSPENDED = 'suspended', _('Suspended')
    ARCHIVED = 'archived', _('Archived')


class Brand(BaseModel):
    """
    Model representing a brand managed by an agency
    """
    name = models.CharField(
        max_length=255,
        verbose_name=_('Brand Name'),
        help_text=_('The official name of the brand'),
        db_index=True  # Index for faster searches
    )

    agency = models.ForeignKey(
        'agencies.Agency',  # String reference to avoid circular imports
        on_delete=models.CASCADE,  # Better than DO_NOTHING - maintains data integrity
        related_name='brands',
        verbose_name=_('Agency'),
        help_text=_('The agency managing this brand')
    )

    description = models.TextField(  # TextField for longer descriptions
        max_length=1000,
        blank=True,
        verbose_name=_('Description'),
        help_text=_('Brief description of the brand')
    )
    
    category = models.CharField(
        max_length=50,
        choices=BrandCategory.choices,
        default=BrandCategory.OTHER,
        verbose_name=_('Category'),
        help_text=_('The industry category of this brand'),
        db_index=True
    )
    
    logo = models.ImageField(  # ImageField instead of CharField for proper file handling
        upload_to=brand_logo_upload_path,
        blank=True,
        null=True,
        validators=[
            FileExtensionValidator(
                allowed_extensions=['jpg', 'jpeg', 'png', 'svg', 'webp']
            )
        ],
        verbose_name=_('Logo'),
        help_text=_('Brand logo image (JPG, PNG, SVG, WebP)')
    )
    
    status = models.CharField(
        max_length=20,
        choices=BrandStatus.choices,
        default=BrandStatus.ACTIVE,
        verbose_name=_('Status'),
        help_text=_('Current status of the brand'),
        db_index=True
    ) 

    is_featured = models.BooleanField(
        default=False,
        verbose_name=_('Featured Brand'),
        help_text=_('Whether this brand should be featured prominently')
    )

    class Meta:
        db_table = 'brands'  # Lowercase table name following Django conventions
        verbose_name = _('Brand')
        verbose_name_plural = _('Brands')
        ordering = ['name']
        unique_together = [['name', 'agency']]  # Prevent duplicate brand names per agency
        indexes = [
            models.Index(fields=['name', 'agency']),
            models.Index(fields=['category', 'status']),
            models.Index(fields=['-created_at']),  # Assuming BaseModel has created_at
        ]

    def __str__(self):
        return f"{self.name} ({self.agency.name if self.agency else 'No Agency'})"

    def clean(self):
        """Custom validation"""
        from django.core.exceptions import ValidationError
        super().clean()
        
        if self.name:
            self.name = self.name.strip() 
 

    def save(self, *args, **kwargs):
        """Override save to perform additional operations"""
        self.full_clean()  # Run validation
        super().save(*args, **kwargs)

    @property
    def logo_url(self):
        """Get the logo URL safely with default fallback"""
        from django.templatetags.static import static
        
        if self.logo and hasattr(self.logo, 'url'):
            return self.logo.url 
        # Return default logo from static files
        return static('images/default-brand-logo.png')

    @property
    def is_active(self):
        """Check if brand is active"""
        return self.status == BrandStatus.ACTIVE  
 