from django.db import models
from django.utils.text import slugify
from django.urls import reverse
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.auth import get_user_model
from jobs.image_utils import compress_and_resize_inplace
from jobs.utils import apply_videsh_chalo_watermark

User = get_user_model()

class BlogCategory(models.Model):
    """Blog ki categories (Visa, Checklist, etc.)"""
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)
    icon = models.CharField(max_length=50, help_text="FontAwesome icon class (e.g., fa-passport)", default="fa-book")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Blog Categories"

class BlogPost(models.Model):
    """Videsh Chalo Gyan Kendra (Blog) ka main model"""
    
    CATEGORY_CHOICES = [
        ('visa', 'Visa Guides'),
        ('living', 'Living Standards'),
        ('checklist', 'Immigration Checklist'),
        ('embassy', 'Embassy Updates'),
        ('general', 'General Guidelines'),
    ]

    title = models.CharField(max_length=255, help_text="SEO Friendly Title (e.g., How to apply for Russia Visa)")
    slug = models.SlugField(unique=True, max_length=255, blank=True)
    author = models.CharField(max_length=100, default="Videsh Chalo Expert Panel")
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='general')
    
    featured_image = models.ImageField(upload_to='blog_images/', help_text="Premium quality image for the guide")
    
    # ✅ NEW: Image Alt Field for SEO
    featured_image_alt = models.CharField(
        max_length=255, 
        blank=True, 
        help_text="Image ke liye SEO alt text (Google Image search ke liye zaroori)"
    )
    
    content = RichTextUploadingField(config_name='default')
    
    # Engagement Fields
    reading_time = models.PositiveIntegerField(help_text="Minutes mein batayein (e.g., 5)")
    short_summary = RichTextField(max_length=700, help_text="User ko attract karne ke liye chota nichod")
    # SEO Section
    meta_title = models.CharField(max_length=255, blank=True)
    meta_description = models.TextField(max_length=160, blank=True)
    meta_keywords = models.CharField(max_length=255, blank=True, help_text="Comma se separate karein")

    # Status & Stats
    is_published = models.BooleanField(default=False)
    views_count = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        # --- PHASE 1: 🔗 AUTO-SLUG LOGIC ---
        if not self.slug:
            self.slug = slugify(self.title)
        
        # --- PHASE 2: 💾 DATABASE SAVE ---
        # Pehle save taaki physical path (self.featured_image.path) mil sake
        super().save(*args, **kwargs)

        # --- PHASE 3: 🚀 SURGICAL IMAGE PROCESSING (Anti-Duplicate) ---
        if self.featured_image:
            try:
                # 1. Surgical Compression (In-place Overwrite)
                # Ise 'jobs.image_utils' se import karna hoga agar ye blog app mein hai
                from jobs.image_utils import compress_and_resize_inplace
                compress_and_resize_inplace(self.featured_image, max_width=1200, quality=75)

                # 2. Dynamic Watermarking (Post-Compression)
                # Note: Watermark logic ko hum physical path par hi chala rahe hain
                from jobs.utils import apply_videsh_chalo_watermark
                apply_videsh_chalo_watermark(self.featured_image.path)
                
                print(f"SUCCESS: Blog Image Optimized and Watermarked for: {self.title}")
                
            except Exception as e:
                print(f"CRITICAL: Blog Image Processing Error: {e}")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        # Reverse mapping according to blog urls
        return reverse('blog_detail', kwargs={'category': self.category, 'slug': self.slug})

    class Meta:
        ordering = ['-created_at']
        verbose_name = "Gyan Kendra Guide"
        verbose_name_plural = "Gyan Kendra Guides"