"""Verify before parsing or accepting a webhook. Cache event IDs to deduplicate."""
import hashlib
import hmac
import time


def verify_webhook(secret, timestamp, signature_header, raw_body, clock=None):
    try:
        sent_at = int(timestamp)
    except (TypeError, ValueError):
        return False
    if abs((time.time() if clock is None else clock) - sent_at) > 300:
        return False
    expected = hmac.new(secret.encode("utf-8"), timestamp.encode("ascii") + b"." + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(part.strip(), "v1=" + expected)
               for part in signature_header.split(","))
