import datetime
import json

from django_celery_results.models import TaskResult
from rest_framework import serializers


class TaskResultSerializer(serializers.ModelSerializer):
    class Meta:
        model = TaskResult
        fields = '__all__'

    def parse_task_kwargs(self, raw: str) -> dict:
        if raw.startswith('"') and raw.endswith('"'):
            raw = raw[1:-1]
        try:
            return eval(raw, {"__builtins__": {}}, {"datetime": datetime})
        except Exception:
            return raw

    def parse_task_result(self, raw: str) -> dict:
        try:
            return json.loads(raw)
        except json.JSONDecodeError:
            return raw

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['task_kwargs'] = self.parse_task_kwargs(instance.task_kwargs)
        data['result'] = self.parse_task_result(instance.result)
        return data
