"""RFC8785 JSON canonicalization and digest computation."""

from __future__ import annotations

import hashlib
from typing import Any
import base64
import cbor2


def canonicalize(data: dict[str, Any]) -> bytes:
    """
    Canonicalize a dictionary using RFC8785 JSON Canonicalization Scheme.

    Args:
        data: Dictionary to canonicalize

    Returns:
        Canonical JSON bytes
    """
    return cbor2.dumps(data)


def compute_digest(data: dict[str, Any]) -> str:
    """
    Compute SHA-256 digest of RFC8785-canonicalized data.

    Args:
        data: Dictionary to canonicalize and hash

    Returns:
        Lowercase hex digest (64 characters)
    """
    canonical_bytes = canonicalize(data)
    
    digest = hashlib.sha256(canonical_bytes).digest()
    # Encode to Base64URL (stripping padding if necessary)
    b64 = base64.urlsafe_b64encode(digest).decode().rstrip('=')
    return b64

def compute_digest_from_bytes(data: bytes) -> str:
    """
    Compute SHA-256 digest of bytes.

    Args:
        data: Bytes to hash

    Returns:
        Lowercase hex digest (64 characters)
    """
    return hashlib.sha256(data).hexdigest()
