from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.utils.text import slugify

class Category(models.Model):
    """Catégorie pour classer les articles (ex: 'Intelligence Artificielle', 'Dev', 'News')."""
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)

    class Meta:
        verbose_name = _("Catégorie")
        verbose_name_plural = _("Catégories")

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)


class Article(models.Model):
    """Article de blog ou étude de cas."""
    STATUS_CHOICES = (
        ('draft', _('Brouillon')),
        ('published', _('Publié')),
    )

    title = models.CharField(max_length=200, verbose_name=_("Titre"))
    slug = models.SlugField(max_length=200, unique=True, verbose_name=_("URL Slug"))
    
    # Classification
    category = models.ForeignKey(
        Category, 
        on_delete=models.SET_NULL, 
        null=True, 
        related_name='articles',
        verbose_name=_("Catégorie")
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, 
        on_delete=models.CASCADE,
        related_name='articles',
        verbose_name=_("Auteur")
    )

    # Contenu
    excerpt = models.TextField(
        max_length=300, 
        blank=True, 
        help_text=_("Court résumé pour les cartes d'aperçu (SEO)."),
        verbose_name=_("Extrait")
    )
    content = models.TextField(
        verbose_name=_("Contenu HTML"),
        help_text=_("Le corps de l'article. Accepte le HTML brut.")
    )
    featured_image = models.ImageField(
        upload_to='blog/images/', 
        blank=True, 
        null=True,
        verbose_name=_("Image à la une")
    )

    # Publication
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
    published_at = models.DateTimeField(null=True, blank=True, verbose_name=_("Date de publication"))
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-published_at', '-created_at'] # Les plus récents en premier
        verbose_name = _("Article")
        verbose_name_plural = _("Articles")

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)