import json
from typing import Any, Protocol

from adaptix import Retort

from redix.types import DefaultRedisType, TypeHintResult


class SerializerProtocol(Protocol):
    def serialize(self, value: Any, tp: TypeHintResult) -> str:
        ...

    def deserialize(self, value: DefaultRedisType, tpr: TypeHintResult) -> Any:
        ...


class Serializator:
    def __init__(self, retort: Retort | None = None) -> None:
        self.retort = retort or Retort()

    def serialize(self, value: Any, tp: TypeHintResult) -> str:
        data = self.retort.dump(value, tp)
        return json.dumps(data)

    def deserialize(self, value: DefaultRedisType, tpr: TypeHintResult) -> Any:
        if isinstance(value, str):
            value = json.loads(value)
            return self.retort.load(value, tpr)
        return value
