# This file was automatically generated by scripts/templates/deserialize.py.jinja2.
# DO NOT MODIFY IT BY HAND. Instead, modify scripts/templates/deserialize.py.jinja2,
# run python ./scripts/generate.py to regenerate this file.
"""This module contains functions for deserializing msgpack encoded wrap manifests."""

from typing import Optional

from polywrap_msgpack import msgpack_decode
from pydantic import ValidationError

from .errors import DeserializeManifestError
from .manifest import *


def deserialize_wrap_manifest(
    manifest: bytes, options: Optional[DeserializeManifestOptions] = None
) -> AnyWrapManifest:
    """Deserialize a wrap manifest from bytes.

    Args:
        manifest: The manifest to deserialize.
        options: Options for deserialization. Defaults to None.

    Raises:
        MsgpackDecodeError: If the manifest could not be decoded.
        DeserializeManifestError: If the manifest could not be deserialized.
        NotImplementedError: If no_validate is set to true or \
            the manifest version is not implemented.

    Returns:
        AnyWrapManifest: The Result of deserialized manifest.
    """
    decoded_manifest = msgpack_decode(manifest)
    if not decoded_manifest.get("version"):
        raise DeserializeManifestError("Expected manifest version to be defined!")

    no_validate = options and options.no_validate
    try:
        manifest_version = WrapManifestVersions(decoded_manifest["version"])
    except ValueError as err:
        raise DeserializeManifestError(
            f"Invalid wrap manifest version: {decoded_manifest['version']}"
        ) from err
    match manifest_version.value:
        case "0.1":
            if no_validate:
                raise NotImplementedError("No validate not implemented for 0.1")
            try:
                return WrapManifest_0_1.validate(decoded_manifest)
            except ValidationError as err:
                raise DeserializeManifestError("Invalid manifest") from err
        case _:
            raise NotImplementedError(
                f"Version {manifest_version.value} is not implemented"
            )


__all__ = ["deserialize_wrap_manifest"]
