from rest_framework.serializers import ModelSerializer, SerializerMethodField

from apps.accounts.serializers import OrganizationSerializer, RoleSerializer, UserSerializer
from apps.knowledge.models import RoleRagDocument, TrainingFile

class TrainingFileSerializer(ModelSerializer):
    uploaded_by = UserSerializer(read_only=True)
    organization = OrganizationSerializer(read_only=True)
    role = RoleSerializer(read_only=True)
    file_url = SerializerMethodField()
    scope = SerializerMethodField()

    class Meta:
        model = TrainingFile
        fields = [
            'id', 'uuid', 'organization', 'role', 'scope', 'uploaded_by', 'file', 'file_url',
            'file_name', 'file_size', 'file_type', 'description', 
            'status', 'is_processed', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'uuid', 'uploaded_by', 'file_size', 'file_type', 
            'status', 'is_processed', 'created_at', 'updated_at',
            'organization', 'role', 'scope'
        ]

    def get_file_url(self, obj: TrainingFile):
        request = self.context.get('request')
        if obj.file and request:
            return request.build_absolute_uri(obj.file.url)
        return obj.file.url if obj.file else None

    def get_scope(self, obj: TrainingFile) -> str:
        return 'role' if obj.role_id else 'organization'

class RoleRagDocumentSerializer(ModelSerializer):
    training_file_name = SerializerMethodField()

    class Meta:
        model = RoleRagDocument
        fields = [
            'id', 'uuid', 'role', 'training_file', 'training_file_name', 
            'content', 'content_hash', 'metadata', 'chunk_index', 
            'is_active', 'created_at'
        ]
        read_only_fields = ['id', 'uuid', 'content_hash', 'created_at']

    def get_training_file_name(self, obj: RoleRagDocument) -> str:
        return obj.training_file.file_name if obj.training_file else None
