"""Tamper-evident receipt model with hash chaining.

Each receipt links to the previous via SHA-256, producing an
append-only chain that can be verified for integrity.
"""

from __future__ import annotations

import hashlib
import json
import uuid
from dataclasses import asdict, dataclass
from typing import Any

_GENESIS_HASH = "0" * 64


@dataclass(frozen=True)
class AuditReceipt:
    """A single tamper-evident audit record ready for export."""

    idempotency_key: str
    payload: dict[str, Any]
    prev_hash: str
    receipt_hash: str

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)


def mint_receipt(
    payload: dict[str, Any],
    prev_hash: str = _GENESIS_HASH,
    idempotency_key: str | None = None,
) -> AuditReceipt:
    """Create a hash-chained audit receipt.

    Args:
        payload: The audit entry data to wrap.
        prev_hash: Hash of the previous receipt in the chain.
        idempotency_key: Unique key for deduplication. Auto-generated if omitted.

    Returns:
        An AuditReceipt with a deterministic receipt_hash.
    """
    key = idempotency_key or uuid.uuid4().hex
    canonical = json.dumps(
        {"idempotency_key": key, "payload": payload, "prev_hash": prev_hash},
        sort_keys=True,
        separators=(",", ":"),
    )
    receipt_hash = hashlib.sha256(canonical.encode()).hexdigest()

    return AuditReceipt(
        idempotency_key=key,
        payload=payload,
        prev_hash=prev_hash,
        receipt_hash=receipt_hash,
    )
