from django.db import models
from django.conf import settings
from django.utils.text import slugify
from django.utils import timezone
from tinymce.models import HTMLField


# ─── Choix de langues centralisé ────────────────────────────────────────────
LANGUAGE_CHOICES = [
    ('fr', 'Français'),
    ('ar', 'العربية'),
]


# ─── Category ───────────────────────────────────────────────────────────────
class Category(models.Model):

    slug = models.SlugField(
        unique=True,
        max_length=150,
        help_text="Identifiant URL unique (ex: economie, technologie)"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Catégorie"
        verbose_name_plural = "Catégories"
        ordering = ['slug']

    def __str__(self):
        return self.slug

    def get_name(self, lang='fr'):
        """Retourne le nom traduit de la catégorie."""
        translation = self.translations.filter(language=lang).first()
        return translation.name if translation else self.slug


class CategoryTranslation(models.Model):

    category = models.ForeignKey(
        Category,
        related_name="translations",
        on_delete=models.CASCADE
    )
    language = models.CharField(
        max_length=10,
        choices=LANGUAGE_CHOICES,
        help_text="Langue de la traduction"
    )
    name = models.CharField(
        max_length=150,
        help_text="Nom de la catégorie dans cette langue"
    )

    class Meta:
        verbose_name = "Traduction de catégorie"
        verbose_name_plural = "Traductions de catégorie"
        constraints = [
            models.UniqueConstraint(
                fields=['category', 'language'],
                name='unique_category_translation'
            )
        ]

    def __str__(self):
        return f"{self.category.slug} ({self.get_language_display()})"


# ─── Article ────────────────────────────────────────────────────────────────
class Article(models.Model):

    STATUS_CHOICES = [
        ('draft', 'Brouillon'),
        ('published', 'Publié'),
    ]

    # Relations
    category = models.ForeignKey(
        Category,
        on_delete=models.PROTECT,
        related_name='articles',
        verbose_name="Catégorie"
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name="Auteur"
    )

    # Core (non traduisible)
    slug = models.SlugField(
        unique=True,
        max_length=250,
        blank=True,
        help_text="Laissez vide pour générer automatiquement depuis le titre FR"
    )
    thumbnail = models.ImageField(
        upload_to='articles/thumbnails/',
        blank=True,
        verbose_name="Vignette",
        help_text="Image de couverture de l'article"
    )
    # Metadata
    is_adherent = models.BooleanField(
        default=False,
        verbose_name="Réservé aux adhérents",
        help_text="Cochez si cet article ne doit être vu que par les membres APECB actifs"
    )
    is_pinned = models.BooleanField(
        default=False,
        verbose_name="Épinglé",
        help_text="Mettre en avant sur l'accueil"
    )

    # Dates
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Créé le")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="Modifié le")
    published_date = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name="Date de publication"
    )

    status = models.CharField(
        max_length=10,
        choices=STATUS_CHOICES,
        default='draft',
        verbose_name="Statut"
    )

    class Meta:
        verbose_name = "Article"
        verbose_name_plural = "Articles"
        ordering = ['-created_at']

    def save(self, *args, **kwargs):
        # Auto-set publication date when publishing
        if self.status == 'published' and not self.published_date:
            self.published_date = timezone.now()

        # Generate slug from FR title if not set and article already has an ID
        if not self.slug and self.pk:
            translation = self.translations.filter(language='fr').first()
            if translation:
                base_slug = slugify(translation.title)
                self.slug = self._get_unique_slug(base_slug)

        # Fallback slug for brand new articles without a slug
        if not self.slug:
            self.slug = slugify(f"article-{timezone.now().timestamp()}")

        super().save(*args, **kwargs)

    def _get_unique_slug(self, base_slug):
        """Ensure slug uniqueness by appending a counter if needed."""
        slug = base_slug
        counter = 1
        while Article.objects.filter(slug=slug).exclude(pk=self.pk).exists():
            slug = f"{base_slug}-{counter}"
            counter += 1
        return slug

    def regenerate_slug(self):
        """
        Regenerate slug from the FR translation title.
        Call this after creating/updating the FR translation.
        """
        translation = self.translations.filter(language='fr').first()
        if translation:
            base_slug = slugify(translation.title)
            self.slug = self._get_unique_slug(base_slug)
            self.save(update_fields=['slug'])

    def __str__(self):
        translation = self.translations.filter(language='fr').first()
        if translation:
            return translation.title
        return self.slug

    def get_title(self, lang='fr'):
        """Retourne le titre traduit de l'article."""
        translation = self.translations.filter(language=lang).first()
        return translation.title if translation else self.slug


class ArticleTranslation(models.Model):

    article = models.ForeignKey(
        Article,
        related_name="translations",
        on_delete=models.CASCADE
    )
    language = models.CharField(
        max_length=10,
        choices=LANGUAGE_CHOICES,
        help_text="Langue de la traduction"
    )

    # Contenu
    title = models.CharField(max_length=250, verbose_name="Titre")
    content = HTMLField(verbose_name="Contenu")
    excerpt = models.TextField(
        max_length=500,
        help_text="Résumé pour cartes et SEO",
        verbose_name="Extrait"
    )

    # SEO
    meta_title = models.CharField(
        max_length=60,
        blank=True,
        verbose_name="Meta titre",
        help_text="Titre SEO (60 caractères max)"
    )
    meta_description = models.CharField(
        max_length=160,
        blank=True,
        verbose_name="Meta description",
        help_text="Description SEO (160 caractères max)"
    )
    keywords = models.CharField(
        max_length=255,
        blank=True,
        verbose_name="Mots-clés",
        help_text="Mots-clés séparés par des virgules"
    )

    class Meta:
        verbose_name = "Traduction d'article"
        verbose_name_plural = "Traductions d'article"
        constraints = [
            models.UniqueConstraint(
                fields=['article', 'language'],
                name='unique_article_translation'
            )
        ]

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

    def save(self, *args, **kwargs):
        # Auto-fill meta_title from title if empty
        if not self.meta_title:
            self.meta_title = self.title[:60]
        # Auto-fill meta_description from excerpt if empty
        if not self.meta_description:
            self.meta_description = self.excerpt[:160]
        super().save(*args, **kwargs)
