"""Canonical hash — delegates to abi-core RFC 8785 implementation.

This module provides deterministic JSON canonicalization per RFC 8785.
All core hashing logic is delegated to abi-core to ensure cross-repo consistency.
"""
from __future__ import annotations

import hashlib
from typing import Any

try:
    from abi_control_core.sdk.canonical_hash import canonical_hash, canonical_serialize
except ImportError:
    # Fallback for standalone use (testing without abi-core installed)
    import json

    def canonical_serialize(data: dict) -> bytes:
        """Fallback: simple sorted JSON serialization (not RFC 8785 compliant)."""
        return json.dumps(
            data, sort_keys=True, separators=(",", ":"), ensure_ascii=True
        ).encode()

    def canonical_hash(data: dict) -> str:
        """Fallback: SHA-256 of sorted JSON (not RFC 8785 compliant)."""
        return hashlib.sha256(canonical_serialize(data)).hexdigest()


# Repo-specific helpers
def canonical_json(obj: Any) -> str:
    """Serialize an object to deterministic canonical JSON string.

    Delegates to abi-core's RFC 8785 implementation via canonical_serialize.
    """
    return canonical_serialize(obj).decode("utf-8")


def sha256_bytes(data: bytes) -> str:
    """Compute SHA-256 of raw bytes."""
    return hashlib.sha256(data).hexdigest()
