"""
Gatebook hashing utilities for receipt stamping.

Provides cryptographic hashing of gatebook configuration to enable
verification that predictions used the claimed policy parameters.
"""

from typing import Dict, Any
import hashlib

from receipts.canonicalize import to_jcs_bytes


def compute_gatebook_hash(gatebook: Dict[str, Any]) -> str:
    """
    Compute deterministic SHA-256 hash of gatebook configuration.
    
    Uses JCS (RFC 8785) canonicalization to ensure consistent hashing
    regardless of key ordering or whitespace.
    
    Args:
        gatebook: Gatebook configuration dictionary
        
    Returns:
        Hash string in format "sha256:HEXDIGEST[:16]"
        
    Example:
        >>> gatebook = {"calibration": {"ece_worst_max": 0.03}, "version": "2.0.0"}
        >>> compute_gatebook_hash(gatebook)
        'sha256:a1b2c3d4e5f6g7h8'
    """
    if not isinstance(gatebook, dict):
        raise TypeError(f"Expected dict, got {type(gatebook).__name__}")
    
    # Canonicalize to ensure deterministic ordering (JCS/RFC 8785)
    canonical_bytes = to_jcs_bytes(gatebook)
    
    # Compute SHA-256 hash
    hash_digest = hashlib.sha256(canonical_bytes).hexdigest()
    
    # Return first 16 chars (64 bits) for brevity
    return f"sha256:{hash_digest[:16]}"


def compute_gatebook_version_hash(gatebook: Dict[str, Any]) -> tuple[str, str]:
    """
    Extract version and compute hash from gatebook.
    
    Convenience function that returns both version string and hash
    for stamping receipts.
    
    Args:
        gatebook: Gatebook configuration dictionary
        
    Returns:
        Tuple of (version_string, hash_string)
        
    Example:
        >>> gatebook = {"version": "2.0.0", "calibration": {...}}
        >>> compute_gatebook_version_hash(gatebook)
        ('2.0.0', 'sha256:a1b2c3d4e5f6g7h8')
    """
    version = gatebook.get("version", "unknown")
    hash_str = compute_gatebook_hash(gatebook)
    return str(version), hash_str


def verify_gatebook_hash(gatebook: Dict[str, Any], claimed_hash: str) -> bool:
    """
    Verify that gatebook matches claimed hash.
    
    Args:
        gatebook: Gatebook configuration to verify
        claimed_hash: Hash string from receipt
        
    Returns:
        True if hashes match, False otherwise
        
    Example:
        >>> gatebook = load_gatebook()
        >>> receipt_hash = "sha256:a1b2c3d4e5f6g7h8"
        >>> verify_gatebook_hash(gatebook, receipt_hash)
        True
    """
    if not claimed_hash.startswith("sha256:"):
        return False
    
    actual_hash = compute_gatebook_hash(gatebook)
    return actual_hash == claimed_hash
