import hashlib
import json
from datetime import datetime


def compute_merkle_hash(data: dict, prev_hash: str | None = None) -> str:
    """Compute SHA-256 Merkle hash for a decision receipt."""
    payload = json.dumps(data, sort_keys=True, default=str)
    combined = f"{prev_hash or 'GENESIS'}:{payload}"
    return hashlib.sha256(combined.encode()).hexdigest()


def verify_chain(receipts: list[dict]) -> bool:
    """Verify the integrity of a Merkle chain of decision receipts."""
    if not receipts:
        return True

    for i, receipt in enumerate(receipts):
        expected_prev = receipts[i - 1]["merkle_hash"] if i > 0 else None
        actual_prev = receipt.get("prev_merkle_hash")

        if expected_prev != actual_prev:
            return False

        # Recompute hash without merkle_hash and prev_merkle_hash fields
        data = {k: v for k, v in receipt.items() if k not in ("merkle_hash", "prev_merkle_hash")}
        recomputed = compute_merkle_hash(data, actual_prev)

        if recomputed != receipt["merkle_hash"]:
            return False

    return True
