from rest_framework import serializers

from apps.standards.models import (
    StandardSource,
    StandardCategory,
    Standard,
    StandardCompliance,
    StandardAttachment,
    ActivityType,
)


class StandardSourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = StandardSource
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class StandardCategorySerializer(serializers.ModelSerializer):
    source_name = serializers.CharField(source='source.name', read_only=True, default="")

    class Meta:
        model = StandardCategory
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class ActivityTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = ActivityType
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class StandardSerializer(serializers.ModelSerializer):
    source_name = serializers.CharField(source='source.name', read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    department_names = serializers.SerializerMethodField()
    activity_type_name = serializers.CharField(source='activity_type.name', read_only=True, default="")
    parent_standard_code = serializers.CharField(source='parent_standard.code', read_only=True, default="")

    class Meta:
        model = Standard
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']

    def get_department_names(self, obj):
        return [d.name for d in obj.departments.all()]


class StandardComplianceSerializer(serializers.ModelSerializer):
    hospital_name = serializers.CharField(source='hospital.name_en', read_only=True, default="")
    department_name = serializers.CharField(source='department.name', read_only=True, default="")
    standard_code = serializers.CharField(source='standard.code', read_only=True)
    standard_title = serializers.CharField(source='standard.title', read_only=True)
    assessor_name = serializers.CharField(source='assessor.get_full_name', read_only=True, default="")
    attachment_count = serializers.SerializerMethodField()

    class Meta:
        model = StandardCompliance
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']

    def get_attachment_count(self, obj):
        return obj.attachments.count()


class StandardAttachmentSerializer(serializers.ModelSerializer):
    uploaded_by_name = serializers.CharField(source='uploaded_by.get_full_name', read_only=True, default="")
    standard_code = serializers.SerializerMethodField()

    class Meta:
        model = StandardAttachment
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']

    def get_standard_code(self, obj):
        if obj.compliance:
            return obj.compliance.standard.code
        if obj.standard:
            return obj.standard.code
        return ""
