"""Webhook signature verification."""
from __future__ import annotations

import hashlib
import hmac


def verify_webhook(payload: bytes, signature: str, secret: str) -> bool:
    """
    Verify the X-DialogBrain-Signature header from a webhook request.

    Args:
        payload: Raw request body bytes (do NOT parse before verifying)
        signature: Value of the X-DialogBrain-Signature header ("sha256=...")
        secret: The whsec_... secret from webhook creation

    Returns:
        True if the signature is valid, False otherwise

    Example::

        from dialogbrain import verify_webhook

        @app.post("/webhook")
        async def handle(request: Request):
            body = await request.body()
            sig = request.headers.get("x-dialogbrain-signature", "")
            secret = "whsec_YOUR_SECRET_HERE"

            if not verify_webhook(body, sig, secret):
                raise HTTPException(401, "Invalid signature")

            event = json.loads(body)
            ...
    """
    key = bytes.fromhex(secret.removeprefix("whsec_"))
    expected = "sha256=" + hmac.new(key, payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)
