"""Msgpack codec for A2A envelopes."""

from __future__ import annotations

import msgpack

from a2a_p2p.errors import ProtocolError
from a2a_p2p.protocol.envelope import A2AEnvelope


def encode(envelope: A2AEnvelope) -> bytes:
    """Serialize an A2AEnvelope to msgpack bytes."""
    data = envelope.model_dump(mode="python")
    return msgpack.packb(data, use_bin_type=True)


def decode(raw: bytes) -> A2AEnvelope:
    """Deserialize msgpack bytes to an A2AEnvelope.

    Raises ProtocolError on invalid data.
    """
    try:
        data = msgpack.unpackb(raw, raw=False)
    except Exception as e:
        raise ProtocolError(f"Failed to decode msgpack: {e}") from e

    if not isinstance(data, dict):
        raise ProtocolError(f"Expected dict, got {type(data).__name__}")

    try:
        return A2AEnvelope.model_validate(data)
    except Exception as e:
        raise ProtocolError(f"Invalid envelope: {e}") from e
