from rest_framework.renderers import BaseRenderer
import json
from django.core.serializers.json import DjangoJSONEncoder


class FixtureRenderer(BaseRenderer):
    media_type = "application/json"
    format = "fixture"
    charset = "utf-8"

    def render(self, data, accepted_media_type=None, renderer_context=None):
        if data is None:
            return ""

        if not isinstance(data, list):
            data = [data]

        # Get model from view
        model_name = "unknown"
        if renderer_context and "view" in renderer_context:
            view = renderer_context["view"]
            if hasattr(view, "queryset") and view.queryset is not None:
                model = view.queryset.model
                model_name = f"{model._meta.app_label}.{model._meta.model_name}"

        fixtures = []
        for item in data:
            fixture = {
                "model": model_name,
                "pk": item.get("id"),
                "fields": {k: v for k, v in item.items() if k != "id"},
            }
            fixtures.append(fixture)

        return json.dumps(fixtures, indent=2, cls=DjangoJSONEncoder)
