from rest_framework import serializers
from .models import Status, StatusView
from django.contrib.auth import get_user_model

User = get_user_model()


class StatusViewerSerializer(serializers.ModelSerializer):
    """Serializer for status viewers"""
    viewer_username = serializers.CharField(source='viewer.username', read_only=True)
    viewer_id = serializers.IntegerField(source='viewer.id', read_only=True)
    viewer_profile_image = serializers.SerializerMethodField()

    class Meta:
        model = StatusView
        fields = [
            'id',
            'viewer_id',
            'viewer_username',
            'viewer_profile_image',
            'viewed_at',
        ]

    def get_viewer_profile_image(self, obj):
        if hasattr(obj.viewer, 'profile_image') and obj.viewer.profile_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.viewer.profile_image.url)
            return obj.viewer.profile_image.url
        return None


class StatusSerializer(serializers.ModelSerializer):
    """Main status serializer"""
    user_username = serializers.CharField(source='user.username', read_only=True)
    user_id = serializers.IntegerField(source='user.id', read_only=True)
    user_profile_image = serializers.SerializerMethodField()
    
    # Media URL
    media_url = serializers.SerializerMethodField()
    
    # Engagement
    views_count = serializers.IntegerField(source='views.count', read_only=True)
    is_viewed_by_user = serializers.SerializerMethodField()
    
    # Time info
    time_remaining_seconds = serializers.SerializerMethodField()
    is_expired = serializers.SerializerMethodField()
    
    # Make user read-only
    user = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Status
        fields = [
            'id',
            'user',
            'user_id',
            'user_username',
            'user_profile_image',
            'content',
            'media',
            'media_url',
            'media_type',
            'background_color',
            'created_at',
            'expires_at',
            'views_count',
            'is_viewed_by_user',
            'time_remaining_seconds',
            'is_expired',
        ]
        read_only_fields = ['created_at', 'expires_at', 'user']

    def get_user_profile_image(self, obj):
        if hasattr(obj.user, 'profile_image') and obj.user.profile_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.user.profile_image.url)
            return obj.user.profile_image.url
        return None

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

    def get_is_viewed_by_user(self, obj):
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return StatusView.objects.filter(
                status=obj,
                viewer=request.user
            ).exists()
        return False

    def get_time_remaining_seconds(self, obj):
        return obj.time_remaining()

    def get_is_expired(self, obj):
        return obj.is_expired()


class StatusDetailSerializer(StatusSerializer):
    """Extended serializer with viewers list"""
    viewers = StatusViewerSerializer(source='views', many=True, read_only=True)

    class Meta(StatusSerializer.Meta):
        fields = StatusSerializer.Meta.fields + ['viewers']


class StatusCreateSerializer(serializers.ModelSerializer):
    """Serializer for creating status"""
    
    class Meta:
        model = Status
        fields = [
            'content',
            'media',
            'media_type',
            'background_color',
        ]

    def validate_media_type(self, value):
        """Validate media type"""
        if value not in ['image', 'video', 'text']:
            raise serializers.ValidationError("Invalid media type")
        return value

    def validate(self, data):
        """Validate that at least content or media is provided"""
        if not data.get('content') and not data.get('media'):
            raise serializers.ValidationError(
                "Either content or media must be provided"
            )
        
        # If media is provided, ensure media_type is set correctly
        if data.get('media'):
            # Auto-detect media type from file extension if not provided
            if data.get('media_type') == 'text':
                file_name = data['media'].name.lower()
                if file_name.endswith(('.jpg', '.jpeg', '.png', '.gif', '.webp')):
                    data['media_type'] = 'image'
                elif file_name.endswith(('.mp4', '.mov', '.avi', '.webm')):
                    data['media_type'] = 'video'
        
        return data