"""
智能体模块序列化器
"""
from rest_framework import serializers
from .models import Spirit


class SpiritSerializer(serializers.ModelSerializer):
    """智能体序列化器"""
    
    class Meta:
        model = Spirit
        fields = ['id', 'name', 'avatar', 'prompt', 'memory', 'voice_id', 'is_active', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']


class CreateSpiritSerializer(serializers.ModelSerializer):
    """创建智能体序列化器"""

    voice_id = serializers.CharField(required=False, allow_blank=True, default='')

    class Meta:
        model = Spirit
        fields = ['name', 'avatar', 'prompt', 'memory', 'voice_id']

    def validate(self, data):
        # Bug #47 fix: use .get() to avoid KeyError when voice_id is not provided
        voice_id = data.get('voice_id', '')
        data['voice_id'] = voice_id
        return data

    def validate_prompt(self, value):
        if value and len(value) > 5000:
            raise serializers.ValidationError('提示词不能超过5000个字符')
        return value


class SpiritListSerializer(serializers.ModelSerializer):
    """智能体列表序列化器（不含memory等大字段）"""
    
    class Meta:
        model = Spirit
        fields = ['id', 'name', 'avatar', 'is_active', 'created_at']


class AdminSpiritSerializer(serializers.ModelSerializer):
    """管理端智能体序列化器"""
    
    user_phone = serializers.CharField(source='user.phone', read_only=True)
    
    class Meta:
        model = Spirit
        fields = ['id', 'user', 'user_phone', 'name', 'avatar', 'prompt', 'memory', 'voice_id', 'is_active', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']
