"""Merkle-tree proof verification."""

from __future__ import annotations

import hashlib


def _hash_pair(left: bytes, right: bytes) -> bytes:
    """SHA-256 hash of the concatenation of *left* and *right*."""
    return hashlib.sha256(left + right).digest()


def verify_merkle_proof(
    leaf_hash: str,
    proof: list[dict[str, str]],
    root: str,
) -> bool:
    """Verify a Merkle inclusion proof.

    Parameters
    ----------
    leaf_hash:
        Hex-encoded SHA-256 hash of the leaf node.
    proof:
        Ordered list of sibling nodes from leaf to root. Each entry is a
        dict with ``"hash"`` (hex string) and ``"position"`` (``"left"``
        or ``"right"``), indicating where the sibling sits relative to
        the current node.
    root:
        Hex-encoded expected Merkle root hash.

    Returns
    -------
    bool
        ``True`` if the proof is valid and the leaf belongs to the tree
        with the given root.
    """
    current = bytes.fromhex(leaf_hash)

    for step in proof:
        sibling = bytes.fromhex(step["hash"])
        position = step["position"]

        if position == "left":
            current = _hash_pair(sibling, current)
        elif position == "right":
            current = _hash_pair(current, sibling)
        else:
            raise ValueError(
                f"Invalid proof position: {position!r} (expected 'left' or 'right')"
            )

    return current.hex() == root
