import os
from .models import ChatSession, ChatMessage, KnowledgeBase
from rest_framework import serializers


class ChatMessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChatMessage
        fields = ["id", "role", "content", "language", "timestamp"]


class ChatSessionSerializer(serializers.ModelSerializer):
    messages = ChatMessageSerializer(many=True, read_only=True)
    display_title = serializers.SerializerMethodField()

    class Meta:
        model = ChatSession
        fields = [
            "id",
            "user",
            "title",  # title is writable
            "created_at",
            "updated_at",
            "messages",
            "display_title",
        ]
        read_only_fields = ["user", "created_at", "updated_at", "messages"]

    def get_display_title(self, obj):
        if obj.title and obj.title != "New Chat":
            return obj.title
        first_message = obj.messages.filter(role="user").order_by("timestamp").first()
        if first_message:
            return first_message.content[:30] + (
                "..." if len(first_message.content) > 30 else ""
            )
        return "New Chat"  # Default if no messages yet


class KnowledgeBaseSerializer(serializers.ModelSerializer):
    file_size = serializers.SerializerMethodField()

    class Meta:
        model = KnowledgeBase
        fields = [
            "id",
            "title",
            "document",
            "image",
            "video",
            "audio",
            "uploaded_at",
            "file_size",
        ]
        read_only_fields = ["uploaded_at", "file_size"]

    def get_file_size(self, obj):
        """Calculate file size for any uploaded file"""
        try:
            if obj.document and hasattr(obj.document, "size"):
                return obj.document.size
            elif obj.image and hasattr(obj.image, "size"):
                return obj.image.size
            elif obj.video and hasattr(obj.video, "size"):
                return obj.video.size
            elif obj.audio and hasattr(obj.audio, "size"):
                return obj.audio.size
        except (OSError, AttributeError):
            pass
        return 0
