"""Verify before decoding/processing a Ridian mailbox webhook. No server/runtime dependency."""
import hashlib
import hmac
import json
import re
import time


def verify_webhook(raw_body, timestamp, signature, signing_secret, now=None):
    """Returns signed event metadata. Persist/deduplicate event.id before replying 2xx.

    Use the exact request bytes. Keep the signing secret separate from mailbox access.
    Even verified message IDs grant no permission to retrieve their contents.
    """
    now = time.time() if now is None else now
    if len(raw_body) > 8192 or not timestamp.isascii() or not timestamp.isdigit() or len(timestamp) > 12:
        raise ValueError("Invalid webhook")
    if not re.fullmatch(r"v1=[a-f0-9]{64}", signature):
        raise ValueError("Invalid webhook signature")
    if abs(now - int(timestamp)) > 300:
        raise ValueError("Expired webhook")
    expected = "v1=" + hmac.new(signing_secret.encode("ascii"), timestamp.encode("ascii") + b"." + raw_body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature):
        raise ValueError("Invalid webhook signature")
    return json.loads(raw_body)
