# AUTOGENERATED! DO NOT EDIT! File to edit: ../../../nbs/019_Json_Encode_Decoder.ipynb.

# %% auto 0
__all__ = ['logger', 'json_encoder', 'json_decoder']

# %% ../../../nbs/019_Json_Encode_Decoder.ipynb 1
import json
from typing import *

from pydantic import BaseModel

from ..logger import get_logger
from ..meta import export

# %% ../../../nbs/019_Json_Encode_Decoder.ipynb 4
logger = get_logger(__name__)

# %% ../../../nbs/019_Json_Encode_Decoder.ipynb 6
def _to_json_utf8(o: Any) -> bytes:
    """Converts to JSON and then encodes with UTF-8"""
    if hasattr(o, "model_dump_json"):
        return o.model_dump_json().encode("utf-8")  # type: ignore
    else:
        return json.dumps(o).encode("utf-8")

# %% ../../../nbs/019_Json_Encode_Decoder.ipynb 9
@export("fastkafka.encoder")
def json_encoder(msg: BaseModel) -> bytes:
    """
    Encoder to encode pydantic instances to json string

    Args:
        msg: An instance of pydantic basemodel

    Returns:
        Json string in bytes which is encoded from pydantic basemodel
    """
    return _to_json_utf8(msg)

# %% ../../../nbs/019_Json_Encode_Decoder.ipynb 11
@export("fastkafka.encoder")
def json_decoder(raw_msg: bytes, cls: Type[BaseModel]) -> Any:
    """
    Decoder to decode json string in bytes to pydantic model instance

    Args:
        raw_msg: Bytes message received from Kafka topic
        cls: Pydantic class; This pydantic class will be used to construct instance of same class

    Returns:
        An instance of given pydantic class
    """
    msg_dict = json.loads(raw_msg.decode("utf-8"))

    return cls(**msg_dict)
