"""Proto serialization guard — catch unset required fields before sending."""

from __future__ import annotations

from google.protobuf.message import EncodeError, Message

from radiens_core.exceptions import ConfigurationError


def validate_proto(msg: Message) -> None:
    """Raise :class:`ConfigurationError` if *msg* has unset required fields.

    Proto2 messages can have ``required`` fields that cause opaque
    serialization errors if left unset.  Call this in converters that
    build *request* protos before returning them.

    Parameters
    ----------
    msg
        A protobuf message instance.

    Raises
    ------
    ConfigurationError
        If any required field is not initialized.
    """
    if msg.IsInitialized():
        return

    # Attempt serialization to get a descriptive error message.
    try:
        msg.SerializeToString()
    except EncodeError as exc:
        raise ConfigurationError(str(exc)) from exc

    # Fallback if SerializeToString doesn't raise (shouldn't happen)
    raise ConfigurationError(  # pragma: no cover
        f"{msg.DESCRIPTOR.full_name} has unset required fields"
    )
