"""
DRF serializers for LLM Manager.
"""

from rest_framework import serializers

from ..models import LLMApi, LLMModel, LLMUsage


class LLMApiSerializer(serializers.ModelSerializer):
    model_count = serializers.SerializerMethodField()

    class Meta:
        model = LLMApi
        fields = [
            "id",
            "name",
            "api_type",
            "base_url",
            "is_active",
            "supports_streaming",
            "timeout_seconds",
            "max_retries",
            "last_tested_at",
            "last_test_status",
            "model_count",
            "created_at",
            "updated_at",
        ]
        read_only_fields = [
            "id",
            "last_tested_at",
            "last_test_status",
            "created_at",
            "updated_at",
        ]

    def get_model_count(self, obj):
        return obj.models.filter(is_active=True).count()


class LLMModelSerializer(serializers.ModelSerializer):
    api_name = serializers.CharField(source="api.name", read_only=True)

    class Meta:
        model = LLMModel
        fields = [
            "id",
            "api",
            "api_name",
            "name",
            "display_name",
            "model_type",
            "context_window",
            "max_output_tokens",
            "vector_dimensions",
            "supports_cache",
            "supports_vision",
            "supports_multimodal",
            "supports_function_calling",
            "supports_json_mode",
            "input_cost_per_1k",
            "output_cost_per_1k",
            "cached_cost_per_1k",
            "is_active",
            "is_system_embedding_model",
            "is_system_chat_model",
            "is_system_reranker_model",
            "created_at",
            "updated_at",
        ]
        read_only_fields = [
            "id",
            "is_system_embedding_model",
            "is_system_chat_model",
            "is_system_reranker_model",
            "created_at",
            "updated_at",
        ]


class LLMUsageSerializer(serializers.ModelSerializer):
    model_name = serializers.CharField(source="model.name", read_only=True)
    api_name = serializers.CharField(source="model.api.name", read_only=True)
    username = serializers.CharField(source="user.username", read_only=True)

    class Meta:
        model = LLMUsage
        fields = [
            "id",
            "user",
            "username",
            "model",
            "model_name",
            "api_name",
            "timestamp",
            "input_tokens",
            "output_tokens",
            "cached_tokens",
            "total_cost",
            "session_id",
            "purpose",
            "request_metadata",
        ]
        read_only_fields = ["id", "timestamp", "total_cost"]
