"""Shared network message serialization helpers."""

from __future__ import annotations

import json
from typing import Any


def pack_message(msg: dict[str, Any]) -> bytes:
    try:
        import msgpack

        return msgpack.packb(msg, use_bin_type=True)
    except Exception:
        return json.dumps(msg).encode("utf-8")


def unpack_message(raw: bytes) -> dict[str, Any]:
    try:
        import msgpack

        return msgpack.unpackb(raw, raw=False)
    except Exception:
        return json.loads(raw.decode("utf-8"))
