from rest_framework import serializers

from .models import (
    Article,
    ArticleTranslation,
    Category,
    CategoryTranslation,
)


# ─── Category Serializers ───────────────────────────────────────────────────

class CategoryTranslationSerializer(serializers.ModelSerializer):
    class Meta:
        model = CategoryTranslation
        fields = ['language', 'name']


class CategorySerializer(serializers.ModelSerializer):
    """Category with its translations."""

    translations = CategoryTranslationSerializer(many=True, read_only=True)

    # Convenience fields — filled based on ?lang= query param
    name = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ['id', 'slug', 'name', 'translations', 'created_at']

    def get_name(self, obj):
        lang = self._get_lang()
        translation = obj.translations.filter(language=lang).first()
        return translation.name if translation else obj.slug

    def _get_lang(self):
        request = self.context.get('request')
        if request:
            return request.query_params.get('lang', 'fr')
        return 'fr'


# ─── Article Serializers ────────────────────────────────────────────────────

class ArticleTranslationSerializer(serializers.ModelSerializer):
    language_display = serializers.CharField(
        source='get_language_display',
        read_only=True
    )

    class Meta:
        model = ArticleTranslation
        fields = [
            'language',
            'language_display',
            'title',
            'content',
            'excerpt',
            'meta_title',
            'meta_description',
            'keywords',
        ]


class ArticleListSerializer(serializers.ModelSerializer):
    """Lightweight serializer for article lists (no full content)."""

    category = CategorySerializer(read_only=True)
    author_name = serializers.SerializerMethodField()
    thumbnail_url = serializers.SerializerMethodField()

    # Localized fields — based on ?lang= query param
    title = serializers.SerializerMethodField()
    excerpt = serializers.SerializerMethodField()

    class Meta:
        model = Article
        fields = [
            'id',
            'slug',
            'title',
            'excerpt',
            'thumbnail_url',
            'category',
            'author_name',
            'is_pinned',
            'is_adherent',
            'status',
            'published_date',
            'created_at',
        ]

    def get_title(self, obj):
        lang = self._get_lang()
        translation = obj.translations.filter(language=lang).first()
        return translation.title if translation else obj.slug

    def get_excerpt(self, obj):
        lang = self._get_lang()
        translation = obj.translations.filter(language=lang).first()
        return translation.excerpt if translation else ''

    def get_author_name(self, obj):
        if obj.author:
            full_name = obj.author.get_full_name()
            return full_name if full_name else obj.author.username
        return None

    def get_thumbnail_url(self, obj):
        if obj.thumbnail:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.thumbnail.url)
            return obj.thumbnail.url
        return None

    def _get_lang(self):
        request = self.context.get('request')
        if request:
            return request.query_params.get('lang', 'fr')
        return 'fr'


class ArticleDetailSerializer(serializers.ModelSerializer):
    """Full serializer with all translations and content."""

    category = CategorySerializer(read_only=True)
    translations = ArticleTranslationSerializer(many=True, read_only=True)
    author_name = serializers.SerializerMethodField()
    thumbnail_url = serializers.SerializerMethodField()

    # Localized convenience fields
    title = serializers.SerializerMethodField()
    excerpt = serializers.SerializerMethodField()
    content = serializers.SerializerMethodField()
    meta_title = serializers.SerializerMethodField()
    meta_description = serializers.SerializerMethodField()
    keywords = serializers.SerializerMethodField()

    class Meta:
        model = Article
        fields = [
            'id',
            'slug',
            'title',
            'excerpt',
            'content',
            'meta_title',
            'meta_description',
            'keywords',
            'thumbnail_url',
            'category',
            'translations',
            'author_name',
            'is_pinned',
            'is_adherent',
            'status',
            'published_date',
            'created_at',
            'updated_at',
        ]

    def _is_content_gated(self, obj):
        """Le content doit être masqué si article réservé adhérents ET user non éligible."""
        return obj.is_adherent and not self.context.get('is_eligible', False)

    def to_representation(self, instance):
        """
        Si le content est gated, on vide aussi le champ `content` à l'intérieur
        de chaque entrée du tableau `translations` — sinon le contenu fuite
        via translations[i].content.
        """
        data = super().to_representation(instance)
        if self._is_content_gated(instance):
            for translation in data.get('translations', []):
                translation['content'] = ''
        return data

    def _get_lang(self):
        request = self.context.get('request')
        if request:
            return request.query_params.get('lang', 'fr')
        return 'fr'

    def _get_translation(self, obj):
        lang = self._get_lang()
        return obj.translations.filter(language=lang).first()

    def get_title(self, obj):
        t = self._get_translation(obj)
        return t.title if t else obj.slug

    def get_excerpt(self, obj):
        t = self._get_translation(obj)
        return t.excerpt if t else ''

    def get_content(self, obj):
        if self._is_content_gated(obj):
            return ''
        t = self._get_translation(obj)
        return t.content if t else ''

    def get_meta_title(self, obj):
        t = self._get_translation(obj)
        return t.meta_title if t else ''

    def get_meta_description(self, obj):
        t = self._get_translation(obj)
        return t.meta_description if t else ''

    def get_keywords(self, obj):
        t = self._get_translation(obj)
        return t.keywords if t else ''

    def get_author_name(self, obj):
        if obj.author:
            full_name = obj.author.get_full_name()
            return full_name if full_name else obj.author.username
        return None

    def get_thumbnail_url(self, obj):
        if obj.thumbnail:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.thumbnail.url)
            return obj.thumbnail.url
        return None
