"""
Serializers for admin analytics endpoints.

Provides serialization for RequestMetadata, RequestBreadcrumb,
ApprovalTransactionMetric, and ErrorSummary aggregation.
"""

from rest_framework import serializers

from apps.core.models import (
    ApprovalTransactionMetric,
    RequestBreadcrumb,
    RequestMetadata,
)


class RequestBreadcrumbSerializer(serializers.ModelSerializer):
    """Serializer for request breadcrumb data."""

    class Meta:
        model = RequestBreadcrumb
        fields = [
            "timestamp",
            "category",
            "message",
            "level",
            "sequence_order",
        ]


class RequestMetadataSerializer(serializers.ModelSerializer):
    """
    Serializer for request metadata with nested breadcrumbs.
    
    Supports the expand=request_breadcrumbs query parameter
    to include breadcrumb data in the response.
    """

    request_breadcrumbs = RequestBreadcrumbSerializer(many=True, read_only=True)
    user_id = serializers.CharField(source="user_id", read_only=True, allow_null=True)

    class Meta:
        model = RequestMetadata
        fields = [
            "id",
            "request_id",
            "trace_id",
            "session_id",
            "parent_request_id",
            "action",
            "method",
            "endpoint",
            "request_method",
            "request_path",
            "affected_route",
            "http_status",
            "status_code",
            "response_status",
            "success",
            "started_at",
            "completed_at",
            "duration_ms",
            "response_time_ms",
            "error_type",
            "error_message",
            "error_stack",
            "error_code",
            "error_origin",
            "component_stack",
            "severity",
            "is_resolved",
            "resolved_at",
            "resolved_by",
            "resolution_notes",
            "retry_count",
            "retry_attempts",
            "user_id",
            "user_agent",
            "ip_address_hash",
            "client_version",
            "timezone",
            "referrer",
            "entity_type",
            "entity_id",
            "created_at",
            "request_breadcrumbs",
        ]
        read_only_fields = ["id", "created_at"]

    def to_representation(self, instance):
        """Conditionally include breadcrumbs based on expand parameter."""
        data = super().to_representation(instance)
        request = self.context.get("request")
        
        # Only include breadcrumbs if explicitly expanded
        if request:
            expand = request.query_params.get("expand", "")
            if "request_breadcrumbs" not in expand:
                data.pop("request_breadcrumbs", None)
        
        return data


class RequestMetadataCreateSerializer(serializers.ModelSerializer):
    """Serializer for creating request metadata (log_request_metadata RPC)."""

    breadcrumbs = RequestBreadcrumbSerializer(many=True, required=False)

    class Meta:
        model = RequestMetadata
        fields = [
            "request_id",
            "trace_id",
            "session_id",
            "parent_request_id",
            "action",
            "method",
            "endpoint",
            "request_method",
            "request_path",
            "affected_route",
            "http_status",
            "status_code",
            "response_status",
            "success",
            "completed_at",
            "duration_ms",
            "response_time_ms",
            "error_type",
            "error_message",
            "error_stack",
            "error_code",
            "error_origin",
            "component_stack",
            "severity",
            "retry_count",
            "retry_attempts",
            "user_agent",
            "ip_address_hash",
            "client_version",
            "timezone",
            "referrer",
            "entity_type",
            "entity_id",
            "breadcrumbs",
        ]

    def create(self, validated_data):
        breadcrumbs_data = validated_data.pop("breadcrumbs", [])
        request_metadata = RequestMetadata.objects.create(**validated_data)
        
        for i, breadcrumb_data in enumerate(breadcrumbs_data):
            RequestBreadcrumb.objects.create(
                request_metadata=request_metadata,
                sequence_order=breadcrumb_data.get("sequence_order", i),
                **{k: v for k, v in breadcrumb_data.items() if k != "sequence_order"}
            )
        
        return request_metadata


class RequestMetadataResolveSerializer(serializers.Serializer):
    """Serializer for resolving request metadata errors."""

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


class ApprovalTransactionMetricSerializer(serializers.ModelSerializer):
    """Serializer for approval transaction metrics."""

    class Meta:
        model = ApprovalTransactionMetric
        fields = [
            "id",
            "submission_id",
            "moderator_id",
            "submitter_id",
            "request_id",
            "success",
            "duration_ms",
            "items_count",
            "rollback_triggered",
            "error_code",
            "error_message",
            "error_details",
            "created_at",
        ]
        read_only_fields = ["id", "created_at"]


class ErrorSummarySerializer(serializers.Serializer):
    """
    Read-only serializer for error summary aggregation.
    
    Aggregates error data from RequestMetadata for dashboard display.
    """

    date = serializers.DateField(read_only=True)
    error_type = serializers.CharField(read_only=True)
    severity = serializers.CharField(read_only=True)
    error_count = serializers.IntegerField(read_only=True)
    resolved_count = serializers.IntegerField(read_only=True)
    affected_users = serializers.IntegerField(read_only=True)
    avg_resolution_minutes = serializers.FloatField(read_only=True, allow_null=True)
