"""JSON message serialization for Cthulhu Remote."""

import json
from enum import Enum
from typing import Any


class JSONSerializer:
    """Serialize newline-delimited JSON remote messages."""

    separator = b"\n"

    def serialize(self, messageType=None, **payload: Any) -> bytes:
        if isinstance(messageType, Enum):
            messageType = messageType.value
        payload["type"] = messageType
        return json.dumps(payload).encode("utf-8") + self.separator

    def deserialize(self, data: bytes) -> dict[str, Any]:
        return json.loads(data.decode("utf-8"))
