"""
Models for Django Lotus Extras.

Provides additional models to extend django-blog-lotus functionality:
- ArticleCoverStyle: Custom background colors for article covers
- BlogCallToAction: Reusable CTA blocks for articles
- ArticleCallToAction: Links CTAs to specific articles
- ArticleViewCount: Tracks view counts for popularity widgets
"""

from django.db import models
from django.utils.translation import gettext_lazy as _

from .conf import django_blog_plus_settings


class ArticleCoverStyle(models.Model):
    """
    Custom styling options for blog article covers.
    Links to django-blog-lotus Article model by ID.
    """
    article_id = models.IntegerField(
        unique=True,
        help_text=_('The ID of the Lotus Article this style applies to')
    )
    background_color = models.CharField(
        max_length=7,
        choices=django_blog_plus_settings.get_cover_bg_colors(),
        default=django_blog_plus_settings.DEFAULT_COVER_BG_COLOR,
        help_text=_('Background color for the article cover image container')
    )
    custom_color = models.CharField(
        max_length=7,
        blank=True,
        null=True,
        help_text=_('Custom hex color (e.g., #FF5733). Overrides background_color if set.')
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = _('Article Cover Style')
        verbose_name_plural = _('Article Cover Styles')

    def __str__(self):
        return f'Cover Style for Article #{self.article_id}'

    def get_background_color(self):
        """Returns the effective background color (custom or preset)."""
        if self.custom_color:
            return self.custom_color
        return self.background_color


class BlogCallToAction(models.Model):
    """
    Reusable Call to Action blocks for blog articles.
    Admins can create multiple CTAs and assign one (or none) to each article.
    """
    title = models.CharField(
        max_length=200,
        help_text=_('CTA section title (e.g., "How Our Product Fits In")')
    )
    image = models.ImageField(
        upload_to='blog/cta/',
        blank=True,
        null=True,
        help_text=_('Optional image to display in the CTA')
    )
    text = models.TextField(
        help_text=_('CTA body text (HTML supported)')
    )
    button_text = models.CharField(
        max_length=50,
        blank=True,
        default='',
        help_text=_('Button label (e.g., "Get Started", "Learn More")')
    )
    button_url = models.URLField(
        blank=True,
        default='',
        help_text=_('Button link URL')
    )
    is_active = models.BooleanField(
        default=True,
        help_text=_('Inactive CTAs will not be displayed even if assigned to articles')
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = _('Blog Call to Action')
        verbose_name_plural = _('Blog Calls to Action')
        ordering = ['-created_at']

    def __str__(self):
        status = '✓' if self.is_active else '✗'
        return f'{status} {self.title}'


class ArticleCallToAction(models.Model):
    """
    Links a Lotus Article to a specific CTA.
    Each article can have at most one CTA assigned.
    """
    article_id = models.IntegerField(
        unique=True,
        help_text=_('The ID of the Lotus Article this CTA is assigned to')
    )
    cta = models.ForeignKey(
        BlogCallToAction,
        on_delete=models.CASCADE,
        related_name='article_assignments',
        help_text=_('The CTA to display at the end of the article')
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = _('Article CTA Assignment')
        verbose_name_plural = _('Article CTA Assignments')

    def __str__(self):
        return f'Article #{self.article_id} → {self.cta.title}'


class ArticleViewCount(models.Model):
    """
    Tracks view counts for blog articles.
    Used to display popular/trending articles widget.
    """
    article_id = models.IntegerField(
        unique=True,
        help_text=_('The ID of the Lotus Article')
    )
    view_count = models.PositiveIntegerField(
        default=0,
        help_text=_('Total number of views')
    )
    last_viewed = models.DateTimeField(
        auto_now=True,
        help_text=_('Last time this article was viewed')
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = _('Article View Count')
        verbose_name_plural = _('Article View Counts')
        ordering = ['-view_count']

    def __str__(self):
        return f'Article #{self.article_id}: {self.view_count} views'

    @classmethod
    def increment_view(cls, article_id):
        """Increment the view count for an article."""
        obj, created = cls.objects.get_or_create(article_id=article_id)
        obj.view_count += 1
        obj.save(update_fields=['view_count', 'last_viewed'])
        return obj
