from django.conf import settings
from rest_framework import serializers

from .models import Asset, AssetFile
from .storage import TosStorage


_tos_storage = None


def _tos():
    global _tos_storage
    if _tos_storage is None:
        _tos_storage = TosStorage()
    return _tos_storage


class AssetFileSerializer(serializers.ModelSerializer):
    preview_url = serializers.SerializerMethodField()

    class Meta:
        model = AssetFile
        fields = [
            "id",
            "object_key",
            "bucket",
            "content_type",
            "size_bytes",
            "width",
            "height",
            "duration_ms",
            "preview_url",
            "is_primary",
        ]
        read_only_fields = [
            "id",
            "object_key",
            "bucket",
            "content_type",
            "size_bytes",
            "width",
            "height",
            "duration_ms",
            "is_primary",
        ]

    def get_preview_url(self, obj):
        # 存储字段优先(如外部已写入绝对 URL);否则用 object_key 实时签发 TOS 预签名 GET URL
        if obj.preview_url:
            return obj.preview_url
        if not obj.object_key or not settings.TOS.get("endpoint"):
            return ""
        try:
            return _tos().presigned_get_url(object_key=obj.object_key)
        except Exception:
            return ""


class AssetSerializer(serializers.ModelSerializer):
    files = AssetFileSerializer(many=True, read_only=True)

    class Meta:
        model = Asset
        fields = [
            "id",
            "name",
            "asset_type",
            "source",
            "category",
            "description",
            "metadata",
            "is_deleted",
            "files",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "created_at", "updated_at"]


class AssetUploadSerializer(serializers.Serializer):
    file = serializers.FileField()
    name = serializers.CharField(max_length=255, required=False, allow_blank=True)
    asset_type = serializers.ChoiceField(choices=Asset.Type.choices)
    category = serializers.ChoiceField(choices=Asset.Category.choices, default=Asset.Category.UPLOAD)
    description = serializers.CharField(required=False, allow_blank=True)

