from __future__ import annotations

"""
Deterministic CBOR helpers for receipt envelopes.

This module provides a thin wrapper around ``cbor2`` to ensure all payloads are
encoded with canonical ordering (RFC 8949, section 4.2) so that round-trips
produce identical byte strings. The helper also exposes a SHA-256 digest
utility for integrity manifests.
"""

import hashlib
from typing import Any

import cbor2

__all__ = ["encode", "decode", "sha256_digest"]


def encode(node: Any) -> bytes:
    """Return canonical CBOR bytes for ``node``."""
    # canonical=True enforces deterministic map ordering and float encoding.
    return cbor2.dumps(node, canonical=True)


def decode(data: bytes) -> Any:
    """Decode CBOR bytes produced by :func:`encode`."""
    return cbor2.loads(data)


def sha256_digest(data: bytes) -> str:
    """Return the lowercase hex SHA-256 digest for ``data``."""
    return hashlib.sha256(data).hexdigest()
