from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField
from taggit.managers import TaggableManager
from PIL import Image

class Category(models.Model):
    name        = models.CharField(max_length=100)
    slug        = models.SlugField(unique=True)
    description = models.TextField(blank=True)
    icon        = models.CharField(max_length=50, blank=True)  # Unicode symbol or emoji
    cover_image = models.ImageField(upload_to='categories/', blank=True)
    order       = models.PositiveSmallIntegerField(default=0)
    is_active   = models.BooleanField(default=True)
    meta_description = models.TextField(blank=True)

    # Category colour accent (hex) so each section has its own identity
    accent_color = models.CharField(max_length=7, default='#8b6914')

    class Meta:
        ordering = ['order', 'name']
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.name

class Author(models.Model):
    user        = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True)
    name        = models.CharField(max_length=150)
    slug        = models.SlugField(unique=True)
    bio         = models.TextField(blank=True)
    photo       = models.ImageField(upload_to='authors/', blank=True)
    email       = models.EmailField(blank=True)
    twitter     = models.URLField(blank=True)
    is_external = models.BooleanField(default=False)  # Community contributor

    def __str__(self):
        return self.name

from django.core.validators import FileExtensionValidator

image_validator = FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'])

class Article(models.Model):
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('review', 'Under Review'),
        ('published', 'Published'),
        ('archived', 'Archived'),
    ]
    TYPE_CHOICES = [
        ('article', 'Article'),
        ('video', 'Video Feature'),
        ('gallery', 'Photo Gallery'),
        ('opinion', 'Opinion'),
        ('timeline', 'Historical Timeline'),
    ]

    title           = models.CharField(max_length=300)
    subtitle        = models.CharField(max_length=400, blank=True)
    slug            = models.SlugField(unique=True, max_length=350)
    author          = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
    categories      = models.ManyToManyField(Category, related_name='articles', blank=True)
    tags            = TaggableManager(blank=True)
    content_type    = models.CharField(max_length=20, choices=TYPE_CHOICES, default='article')
    status          = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')

    # Content fields
    body            = RichTextField()                  # CKEditor — main article body
    excerpt         = models.TextField(max_length=500) # Summary / pull quote shown on cards
    featured_image  = models.FileField(upload_to='articles/%Y/%m/', validators=[image_validator])
    image_caption   = models.CharField(max_length=300, blank=True)
    image_credit    = models.CharField(max_length=200, blank=True)

    # Video fields (for video features)
    video_url       = models.URLField(blank=True)      # YouTube/Vimeo embed URL
    video_thumbnail = models.ImageField(upload_to='video_thumbs/', blank=True)

    # Editorial flags — all controllable from admin
    is_featured     = models.BooleanField(default=False)   # Appears in hero
    is_editors_pick = models.BooleanField(default=False)   # Editors' Pick badge
    is_breaking     = models.BooleanField(default=False)   # Breaking/Latest badge
    is_premium      = models.BooleanField(default=False)   # Future paywall flag

    # Historical metadata
    historical_period = models.CharField(max_length=100, blank=True)  # e.g. "World War II"
    historical_date   = models.CharField(max_length=100, blank=True)  # e.g. "September 1939"
    present_connection = models.TextField(blank=True)  # Short note linking past to present
    # Related Content
    related_products = models.ManyToManyField('store.Product', related_name='related_articles', blank=True)
    related_videos   = models.ManyToManyField('core.YouTubeVideo', related_name='related_articles', blank=True)
    magazines        = models.ManyToManyField('store.Product', related_name='tagged_articles', blank=True,
                                              limit_choices_to={'product_type': 'magazine'},
                                              help_text="Magazine issue(s) this story appears in or relates to. "
                                                        "Shown as a magazine card on the article.")

    # SEO
    meta_title      = models.CharField(max_length=200, blank=True)
    meta_description = models.TextField(blank=True)
    og_image        = models.ImageField(upload_to='og/', blank=True)
    seo_keywords    = models.TextField(blank=True, help_text="Comma-separated SEO keywords, e.g. 'Bangladesh history, Mughal Bengal, naming history Dhaka'")
    canonical_url   = models.URLField(blank=True, help_text="Optional canonical URL if this article is syndicated from elsewhere")

    # Timestamps
    published_at    = models.DateTimeField(null=True, blank=True)
    created_at      = models.DateTimeField(auto_now_add=True)
    updated_at      = models.DateTimeField(auto_now=True)

    # Stats
    view_count      = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ['-published_at']
        indexes = [
            models.Index(fields=['status', 'published_at']),
            models.Index(fields=['is_featured', 'status']),
        ]

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        from django.urls import reverse
        return reverse('article_detail', kwargs={'slug': self.slug})

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if self.featured_image and not self.featured_image.name.lower().endswith('.svg'):
            try:
                img = Image.open(self.featured_image.path)
                if img.width > 1200:
                    output_size = (1200, int((1200 / img.width) * img.height))
                    img.thumbnail(output_size)
                    img.save(self.featured_image.path)
            except Exception:
                pass  # Skip if PIL can't process the file

class TimelineEvent(models.Model):
    """For 'Historical Timeline' type articles — a linked list of events"""
    article     = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='timeline_events')
    year        = models.CharField(max_length=20)
    title       = models.CharField(max_length=200)
    description = models.TextField()
    image       = models.ImageField(upload_to='timeline/', blank=True)
    order       = models.PositiveSmallIntegerField(default=0)

    class Meta:
        ordering = ['order']

    def __str__(self):
        return f"{self.year} - {self.title}"

class UserBookmark(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookmarks')
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='bookmarked_by')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        unique_together = ('user', 'article')

    def __str__(self):
        return f"{self.user.username} bookmarked {self.article.title}"

class TodayExclusive(models.Model):
    date = models.DateField(unique=True)
    article = models.ForeignKey(Article, on_delete=models.CASCADE)

    class Meta:
        ordering = ['-date']
        
    def __str__(self):
        return f"Exclusive for {self.date}: {self.article.title}"
