"""
设备模块序列化器
"""
from rest_framework import serializers
from .models import DeviceType, DeviceBatch, Device, UserDevice, DeviceSettings, DeviceWifi, RoleMemory


class DeviceTypeSerializer(serializers.ModelSerializer):
    """设备类型序列化器"""

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

    class Meta:
        model = DeviceType
        fields = ['id', 'brand', 'product_code', 'name', 'is_network_required', 'is_active',
                  'default_prompt', 'default_voice_id', 'created_at']
        read_only_fields = ['id', 'is_network_required', 'created_at']


class DeviceBatchSerializer(serializers.ModelSerializer):
    """设备批次序列化器"""
    
    device_type_info = DeviceTypeSerializer(source='device_type', read_only=True)
    
    class Meta:
        model = DeviceBatch
        fields = ['id', 'device_type', 'device_type_info', 'batch_no', 'production_date', 
                  'production_week', 'quantity', 'remark', 'status', 'created_at']
        read_only_fields = ['id', 'production_week', 'status', 'created_at']


class DeviceBatchCreateSerializer(serializers.ModelSerializer):
    """创建设备批次序列化器"""
    
    class Meta:
        model = DeviceBatch
        fields = ['device_type', 'batch_no', 'production_date', 'quantity', 'remark']


class DeviceSerializer(serializers.ModelSerializer):
    """设备序列化器"""

    device_type = DeviceTypeSerializer(read_only=True)
    device_type_info = DeviceTypeSerializer(source='device_type', read_only=True)

    class Meta:
        model = Device
        fields = ['id', 'sn', 'device_type', 'device_type_info', 'mac_address',
                  'name', 'status', 'firmware_version', 'last_online_at', 'created_at']


class DeviceSimpleSerializer(serializers.ModelSerializer):
    """设备简单序列化器"""
    
    class Meta:
        model = Device
        fields = ['id', 'sn', 'mac_address', 'status', 'created_at']


class RoleMemorySerializer(serializers.ModelSerializer):
    """角色记忆序列化器"""
    device_type_name = serializers.CharField(source='device_type.name', read_only=True)

    class Meta:
        model = RoleMemory
        fields = [
            'id', 'device_type', 'device_type_name', 'is_bound',
            'nickname', 'user_name', 'volume', 'brightness',
            'allow_interrupt', 'privacy_mode',
            'prompt', 'voice_id',
            'memory_summary',
            'created_at', 'updated_at',
        ]
        read_only_fields = ['id', 'device_type', 'device_type_name', 'is_bound',
                            'created_at', 'updated_at']


class UserDeviceSerializer(serializers.ModelSerializer):
    """用户设备绑定序列化器"""

    device = DeviceSerializer(read_only=True)
    spirit_name = serializers.CharField(source='spirit.name', read_only=True, allow_null=True)
    role_memory = RoleMemorySerializer(read_only=True)

    class Meta:
        model = UserDevice
        fields = ['id', 'device', 'spirit', 'spirit_name', 'role_memory',
                  'bind_type', 'bind_time', 'is_active']


class BindDeviceSerializer(serializers.Serializer):
    """绑定设备序列化器"""
    
    sn = serializers.CharField(max_length=50, help_text='设备SN码')
    spirit_id = serializers.IntegerField(required=False, allow_null=True, help_text='智能体ID')


class DeviceVerifySerializer(serializers.Serializer):
    """验证设备SN序列化器"""
    
    sn = serializers.CharField(max_length=50, help_text='设备SN码')


class QueryByMacSerializer(serializers.Serializer):
    """通过MAC查询SN序列化器"""
    
    mac = serializers.CharField(max_length=20, help_text='MAC地址')
    
    def validate_mac(self, value):
        # 统一MAC地址格式
        value = value.upper().replace('-', ':')
        return value


class DeviceSettingsSerializer(serializers.ModelSerializer):
    """设备设置序列化器"""

    class Meta:
        model = DeviceSettings
        fields = ['nickname', 'user_name', 'volume', 'brightness',
                  'allow_interrupt', 'privacy_mode']


class DeviceWifiSerializer(serializers.ModelSerializer):
    """设备WiFi序列化器"""

    class Meta:
        model = DeviceWifi
        fields = ['ssid', 'is_connected']


class DeviceDetailSerializer(serializers.ModelSerializer):
    """设备详情序列化器"""

    settings = DeviceSettingsSerializer(read_only=True)
    wifi_list = DeviceWifiSerializer(many=True, read_only=True)
    status = serializers.SerializerMethodField()
    bound_spirit = serializers.SerializerMethodField()
    role_memory = serializers.SerializerMethodField()

    class Meta:
        model = Device
        fields = ['id', 'sn', 'name', 'status', 'battery', 'firmware_version',
                  'mac_address', 'is_ai', 'icon', 'settings', 'wifi_list',
                  'bound_spirit', 'role_memory']

    def get_status(self, obj):
        return 'online' if obj.is_online else 'offline'

    def get_bound_spirit(self, obj):
        user_device = self.context.get('user_device')
        if user_device and user_device.spirit:
            return {'id': user_device.spirit.id, 'name': user_device.spirit.name}
        return None

    def get_role_memory(self, obj):
        user_device = self.context.get('user_device')
        if user_device and user_device.role_memory:
            return RoleMemorySerializer(user_device.role_memory).data
        return None


class DeviceSettingsUpdateSerializer(serializers.Serializer):
    """更新设备设置序列化器"""
    nickname = serializers.CharField(max_length=50, required=False)
    user_name = serializers.CharField(max_length=50, required=False)
    volume = serializers.IntegerField(min_value=0, max_value=100, required=False)
    brightness = serializers.IntegerField(min_value=0, max_value=100, required=False)
    allow_interrupt = serializers.BooleanField(required=False)
    privacy_mode = serializers.BooleanField(required=False)


class DeviceReportStatusSerializer(serializers.Serializer):
    """设备状态上报序列化器（硬件端使用）"""
    mac_address = serializers.CharField(max_length=20, help_text='MAC地址')
    is_online = serializers.BooleanField(required=False, help_text='是否在线')
    battery = serializers.IntegerField(min_value=0, max_value=100, required=False, help_text='电量百分比')
    volume = serializers.IntegerField(min_value=0, max_value=100, required=False, help_text='音量')
    brightness = serializers.IntegerField(min_value=0, max_value=100, required=False, help_text='亮度')
    firmware_version = serializers.CharField(max_length=20, required=False, help_text='固件版本')

    def validate_mac_address(self, value):
        return value.upper().replace('-', ':')


class RoleMemorySettingsUpdateSerializer(serializers.Serializer):
    """更新角色记忆-设备设置"""
    nickname = serializers.CharField(max_length=50, required=False)
    user_name = serializers.CharField(max_length=50, required=False)
    volume = serializers.IntegerField(min_value=0, max_value=100, required=False)
    brightness = serializers.IntegerField(min_value=0, max_value=100, required=False)
    allow_interrupt = serializers.BooleanField(required=False)
    privacy_mode = serializers.BooleanField(required=False)


class RoleMemoryAgentUpdateSerializer(serializers.Serializer):
    """更新角色记忆-Agent信息"""
    prompt = serializers.CharField(required=False, allow_blank=True)
    voice_id = serializers.CharField(max_length=100, required=False, allow_blank=True)


class RoleMemoryMemoryUpdateSerializer(serializers.Serializer):
    """更新角色记忆-聊天记忆摘要"""
    memory_summary = serializers.CharField(required=True, allow_blank=True)
