
from rest_framework.renderers import JSONRenderer


# custom renderer to fix a horrible python json issue, that corrupts large integers
# issue example: parsing an integer 1204426362794811453 will corrupt the integer into 1204426362794811400.
class FixedJSONRenderer(JSONRenderer):
    def handle_large_ints(self, data):
        if isinstance(data, dict):
            return {
                key: self.handle_large_ints(value)  # Recursively apply to nested dicts
                if isinstance(value, (dict, list)) else str(value)
                if isinstance(value, int) and value > 1000000000000000 else value
                for key, value in data.items()
            }
        elif isinstance(data, list):
            return [
                self.handle_large_ints(item)  # Recursively apply to lists
                if isinstance(item, (dict, list)) else str(item)
                if isinstance(item, int) and item > 1000000000000000 else item
                for item in data
            ]
        return data

    def render(self, data, *args, **kwargs):
        data = self.handle_large_ints(data)  # Preprocess data to convert large ints
        return super().render(data, *args, **kwargs)
