"""Webhook signature verification utility."""

from __future__ import annotations

import hashlib
import hmac


def verify_webhook_signature(
    payload: str | bytes,
    signature: str,
    secret: str,
) -> bool:
    """Verify a Wallgent webhook signature.

    Args:
        payload: The raw request body.
        signature: The ``Wallgent-Signature`` header value (format: ``sha256=<hex>``).
        secret: The webhook secret provided when creating the webhook.

    Returns:
        ``True`` if the signature is valid.
    """
    prefix = "sha256="
    if not signature.startswith(prefix):
        return False

    received_hex = signature[len(prefix):]

    if isinstance(payload, str):
        payload = payload.encode("utf-8")

    expected_hex = hmac.new(
        secret.encode("utf-8"),
        payload,
        hashlib.sha256,
    ).hexdigest()

    return hmac.compare_digest(received_hex, expected_hex)
