from rest_framework import serializers
from drf_spectacular.utils import extend_schema_field
from drf_spectacular.types import OpenApiTypes
from typing import Optional
from sitemanagement.models import Alert

class AlertSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    object = serializers.SerializerMethodField()
    metric_value = serializers.SerializerMethodField()
    detector_type = serializers.SerializerMethodField()
    detector_id = serializers.SerializerMethodField()
    
    class Meta:
        model = Alert
        fields = ('id', 'name', 'object', 'metric_value', 'detector_type', 'detector_id', 'message', 'severity', 'created_at', 'resolved')

    @extend_schema_field(OpenApiTypes.STR)
    def get_name(self, obj) -> str:
        return obj.sensor.name

    @extend_schema_field(OpenApiTypes.STR)
    def get_object(self, obj) -> Optional[str]:
        zone = obj.sensor.zones.first()
        return zone.object.title if zone else None
        
    @extend_schema_field(OpenApiTypes.STR)
    def get_metric_value(self, obj) -> str:
        if obj.metric.value is not None:
            unit = obj.sensor.signal_format.unit if obj.sensor.signal_format else ''
            return f"{obj.metric.value} {unit}".strip()
        return obj.metric.raw_value
    
    @extend_schema_field(OpenApiTypes.STR)
    def get_detector_type(self, obj) -> str: 
        sensor_type = getattr(obj, 'sensor_type', None)
        if sensor_type is None and hasattr(obj, 'sensor') and obj.sensor:
            sensor_type = getattr(obj.sensor, 'sensor_type', None)
        if sensor_type is None:
            return ''
        return (getattr(sensor_type, 'code', '') or '').upper()

    @extend_schema_field(OpenApiTypes.STR)
    def get_detector_id(self, obj) -> str: 
        if hasattr(obj, 'sensor') and obj.sensor: 
            return obj.sensor.name or f"{obj.sensor.sensor_type.code}-{obj.sensor.id}"
        return ""
