"""
Serializers for observability API endpoints.

Provides serializers for PipelineError, Anomaly, AlertCorrelationRule,
CleanupJobLog, and DataRetentionStats.
"""

from rest_framework import serializers

from apps.core.choices.serializers import RichChoiceSerializerField
from apps.core.models import (
    AlertCorrelationRule,
    Anomaly,
    CleanupJobLog,
    PipelineError,
)


class PipelineErrorSerializer(serializers.ModelSerializer):
    """Serializer for pipeline errors."""

    severity = RichChoiceSerializerField(
        choice_group="pipeline_error_severities",
        domain="core",
    )
    resolved_by_username = serializers.CharField(
        source="resolved_by.username",
        read_only=True,
        allow_null=True,
    )

    class Meta:
        model = PipelineError
        fields = [
            "id",
            "function_name",
            "error_message",
            "error_code",
            "error_context",
            "stack_trace",
            "severity",
            "submission_id",
            "item_id",
            "request_id",
            "trace_id",
            "resolved",
            "resolved_by",
            "resolved_by_username",
            "resolved_at",
            "resolution_notes",
            "occurred_at",
        ]
        read_only_fields = ["id", "occurred_at", "resolved_by_username"]


class PipelineErrorResolveSerializer(serializers.Serializer):
    """Serializer for resolving pipeline errors."""

    resolution_notes = serializers.CharField(required=False, allow_blank=True)


class AnomalySerializer(serializers.ModelSerializer):
    """Serializer for detected anomalies."""

    anomaly_type = RichChoiceSerializerField(
        choice_group="anomaly_types",
        domain="core",
    )
    severity = RichChoiceSerializerField(
        choice_group="severity_levels",
        domain="core",
    )
    alert_message = serializers.CharField(
        source="alert.message",
        read_only=True,
        allow_null=True,
    )
    alert_resolved_at = serializers.DateTimeField(
        source="alert.resolved_at",
        read_only=True,
        allow_null=True,
    )
    alert_id = serializers.UUIDField(
        source="alert.id",
        read_only=True,
        allow_null=True,
    )

    class Meta:
        model = Anomaly
        fields = [
            "id",
            "metric_name",
            "metric_category",
            "anomaly_type",
            "severity",
            "anomaly_value",
            "baseline_value",
            "deviation_score",
            "confidence_score",
            "detection_algorithm",
            "time_window_start",
            "time_window_end",
            "alert_created",
            "alert_id",
            "alert_message",
            "alert_resolved_at",
            "detected_at",
        ]
        read_only_fields = [
            "id",
            "detected_at",
            "alert_id",
            "alert_message",
            "alert_resolved_at",
        ]


class AlertCorrelationRuleSerializer(serializers.ModelSerializer):
    """Serializer for alert correlation rules."""

    incident_severity = RichChoiceSerializerField(
        choice_group="severity_levels",
        domain="core",
    )

    class Meta:
        model = AlertCorrelationRule
        fields = [
            "id",
            "rule_name",
            "rule_description",
            "min_alerts_required",
            "time_window_minutes",
            "incident_severity",
            "incident_title_template",
            "is_active",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "created_at", "updated_at"]


class CleanupJobLogSerializer(serializers.ModelSerializer):
    """Serializer for cleanup job logs."""

    status = RichChoiceSerializerField(
        choice_group="cleanup_job_statuses",
        domain="core",
    )

    class Meta:
        model = CleanupJobLog
        fields = [
            "id",
            "job_name",
            "status",
            "records_processed",
            "records_deleted",
            "error_message",
            "duration_ms",
            "executed_at",
        ]
        read_only_fields = ["id", "executed_at"]


class DataRetentionStatsSerializer(serializers.Serializer):
    """Serializer for data retention statistics view."""

    table_name = serializers.CharField()
    total_records = serializers.IntegerField()
    last_7_days = serializers.IntegerField()
    last_30_days = serializers.IntegerField()
    oldest_record = serializers.DateTimeField(allow_null=True)
    newest_record = serializers.DateTimeField(allow_null=True)
    table_size = serializers.CharField()
