from django.db import models
from django.utils.text import slugify
from django.contrib.auth.models import User


class Blog(models.Model):
    """
    Blog model with comprehensive SEO fields and slug management.
    """
    # Main fields
    title = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, unique=True, primary_key=True, db_index=True)
    content = models.TextField()
    
    # Media fields
    thumbnail_image = models.ImageField(upload_to='blog_thumbnails/', help_text='Thumbnail image for blog list')
    thumbnail_image_alt = models.CharField(max_length=255, blank=True, default='', help_text='Alt text for thumbnail image')
    featured_image = models.ImageField(upload_to='blog_images/', help_text='Featured image for blog post')
    featured_image_alt = models.CharField(max_length=255, blank=True, default='', help_text='Alt text for featured image')
    
    # SEO fields
    meta_title = models.CharField(max_length=100, help_text='SEO meta title (60 characters recommended)')
    meta_description = models.CharField(max_length=200, help_text='SEO meta description (160 characters recommended)')
    tags = models.CharField(max_length=255, help_text='Comma-separated tags for SEO')
    
    # Open Graph fields
    og_title = models.CharField(max_length=255, blank=True, help_text='Open Graph title')
    og_description = models.CharField(max_length=200, blank=True, help_text='Open Graph description')
    og_image = models.ImageField(upload_to='blog_og_images/', blank=True, null=True, help_text='Open Graph image')
    og_image_alt = models.CharField(max_length=255, blank=True, help_text='Alt text for OG image')
    
    # Content quality & SEO fields
    word_count = models.IntegerField(default=0, help_text='Total number of words in content')
    reading_time = models.IntegerField(default=0, help_text='Estimated reading time in minutes')
    
    # Author and status
    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='blogs')
    is_featured = models.BooleanField(default=False, help_text='Mark as featured blog')
    is_published = models.BooleanField(default=False, help_text='Publish this blog')
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    published_at = models.DateTimeField(null=True, blank=True, help_text='Date when blog was published')
    
    class Meta:
        ordering = ['-published_at', '-created_at']
        indexes = [
            models.Index(fields=['is_published', '-published_at']),
            models.Index(fields=['is_featured']),
        ]
    
    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        """
        Override save to handle slug generation, collision, and calculate reading time.
        """
        if not self.slug:
            # Generate slug from title
            base_slug = slugify(self.title)
            self.slug = base_slug
            
            # Check for slug collision and add numerical suffix if needed
            counter = 1
            original_slug = base_slug
            while Blog.objects.filter(slug=self.slug).exclude(pk=self.pk).exists():
                self.slug = f"{original_slug}-{counter}"
                counter += 1
        else:
            # If slug is being edited, check for collision
            base_slug = self.slug
            counter = 1
            original_slug = base_slug
            while Blog.objects.filter(slug=self.slug).exclude(pk=self.pk).exists():
                self.slug = f"{original_slug}-{counter}"
                counter += 1
        
        # Calculate word count and reading time
        word_count = len(self.content.split())
        self.word_count = word_count
        # Average reading speed: 200 words per minute
        self.reading_time = max(1, word_count // 200)
        
        # Set published_at if being published
        if self.is_published and not self.published_at:
            from django.utils import timezone
            self.published_at = timezone.now()
        
        super().save(*args, **kwargs)
    
    @property
    def excerpt(self):
        """Get first 150 characters of content as excerpt"""
        return self.content[:150] + '...' if len(self.content) > 150 else self.content
