import hashlib
import hmac
import re
import time


def verify_kiosform_webhook(secret, raw_body, header, now=None):
    """raw_body contient les octets HTTP, avant le décodage JSON."""
    if not secret or not isinstance(raw_body, bytes) or not isinstance(header, str):
        return False
    parts = re.fullmatch(r"t=([1-9][0-9]{0,11}),v1=([a-f0-9]{64})", header)
    if parts is None:
        return False
    timestamp = int(parts[1])
    if abs((time.time() if now is None else now) - timestamp) > 300:
        return False
    signed = (parts[1] + ".").encode("ascii") + raw_body
    expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts[2])
