from rest_framework import serializers
from .models import LiveSession, LiveProductPin, LiveComment


class LiveSessionListSerializer(serializers.ModelSerializer):
    shop_name = serializers.SerializerMethodField()
    shop_logo = serializers.SerializerMethodField()
    shop_slug = serializers.SerializerMethodField()
    vendor_id = serializers.IntegerField(source='vendor.id', read_only=True)
    whatsapp_number = serializers.SerializerMethodField()
    duration = serializers.SerializerMethodField()

    class Meta:
        model = LiveSession
        fields = [
            'id', 'uuid', 'title', 'slug', 'status', 'thumbnail',
            'scheduled_at', 'started_at', 'ended_at',
            'viewer_count', 'peak_viewers', 'total_views',
            'vendor_id', 'shop_name', 'shop_logo', 'shop_slug',
            'whatsapp_number', 'duration',
        ]
        read_only_fields = [
            'id', 'uuid', 'slug', 'viewer_count', 'peak_viewers', 'total_views',
        ]

    def get_shop_name(self, obj):
        try:
            return obj.vendor.vendor_profile.shop_name
        except Exception:
            return obj.vendor.full_name

    def get_shop_logo(self, obj):
        try:
            logo = obj.vendor.vendor_profile.shop_logo
            if logo:
                request = self.context.get('request')
                if request:
                    return request.build_absolute_uri(logo.url)
                return logo.url
        except Exception:
            pass
        return None

    def get_shop_slug(self, obj):
        try:
            return obj.vendor.vendor_profile.slug
        except Exception:
            return ''

    def get_whatsapp_number(self, obj):
        try:
            return obj.vendor.vendor_profile.whatsapp_number
        except Exception:
            return None

    def get_duration(self, obj):
        return obj.duration_seconds


class LiveProductPinSerializer(serializers.ModelSerializer):
    product_id = serializers.IntegerField(source='product.id', read_only=True)
    product_name = serializers.SerializerMethodField()
    product_price = serializers.SerializerMethodField()
    product_image = serializers.SerializerMethodField()
    product_slug = serializers.SerializerMethodField()
    product_category = serializers.SerializerMethodField()

    class Meta:
        model = LiveProductPin
        fields = [
            'id', 'product_id', 'product_name', 'product_price',
            'product_image', 'product_slug', 'product_category',
            'is_currently_pinned', 'order',
        ]

    def get_product_name(self, obj):
        return obj.product.name

    def get_product_price(self, obj):
        return str(obj.product.price)

    def get_product_image(self, obj):
        try:
            img = obj.product.primary_image
            if img:
                request = self.context.get('request')
                if request:
                    return request.build_absolute_uri(img.url)
                return img.url
        except Exception:
            pass
        return None

    def get_product_slug(self, obj):
        return obj.product.slug if hasattr(obj.product, 'slug') else ''

    def get_product_category(self, obj):
        return obj.product.category if hasattr(obj.product, 'category') else ''


class LiveSessionDetailSerializer(LiveSessionListSerializer):
    products = LiveProductPinSerializer(source='product_pins', many=True, read_only=True)

    class Meta(LiveSessionListSerializer.Meta):
        fields = LiveSessionListSerializer.Meta.fields + [
            'products', 'replay_video', 'agora_channel_name',
            'comments_count', 'reactions_count', 'shares_count',
        ]


class LiveSessionCreateSerializer(serializers.ModelSerializer):
    product_ids = serializers.ListField(
        child=serializers.IntegerField(),
        write_only=True,
        required=False,
        default=[],
    )

    class Meta:
        model = LiveSession
        fields = ['title', 'thumbnail', 'scheduled_at', 'notify_followers', 'product_ids']

    def create(self, validated_data):
        product_ids = validated_data.pop('product_ids', [])
        session = LiveSession.objects.create(**validated_data)
        for i, pid in enumerate(product_ids):
            LiveProductPin.objects.create(
                session=session,
                product_id=pid,
                order=i,
            )
        return session


class LiveCommentSerializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    user_photo = serializers.SerializerMethodField()

    class Meta:
        model = LiveComment
        fields = ['id', 'user_name', 'user_photo', 'content', 'created_at']
        read_only_fields = ['id', 'created_at']

    def get_user_name(self, obj):
        return obj.user.full_name

    def get_user_photo(self, obj):
        try:
            photo = obj.user.profile_photo
            if photo:
                request = self.context.get('request')
                if request:
                    return request.build_absolute_uri(photo.url)
                return photo.url
        except Exception:
            pass
        return None


class LiveSummarySerializer(serializers.ModelSerializer):
    duration = serializers.SerializerMethodField()

    class Meta:
        model = LiveSession
        fields = [
            'id', 'uuid', 'title', 'slug', 'status',
            'started_at', 'ended_at', 'duration',
            'viewer_count', 'peak_viewers', 'total_views', 'replay_views',
            'comments_count', 'reactions_count', 'shares_count',
            'new_followers_count', 'product_views_count',
            'whatsapp_clicks', 'call_clicks',
        ]

    def get_duration(self, obj):
        return obj.duration_seconds
