"""Dependency-free Standard Webhooks verification. Pass raw request bytes."""

import base64
import hashlib
import hmac
import json
import time


def verify_webhook(
    raw_body: bytes, headers: dict[str, str], secrets: str | list[str], seen_ids: set[str]
):
    event_id = headers.get("Webhook-Id") or headers.get("webhook-id")
    timestamp = int(headers.get("Webhook-Timestamp") or headers.get("webhook-timestamp") or "0")
    if not event_id or abs(time.time() - timestamp) > 300:
        raise ValueError("stale webhook")
    values = secrets if isinstance(secrets, list) else [secrets]
    valid = False
    for value in (
        headers.get("Webhook-Signature") or headers.get("webhook-signature") or ""
    ).split():
        version, _, supplied = value.partition(",")
        if version != "v1" or not supplied:
            continue
        for secret in values:
            expected = base64.b64encode(
                hmac.new(
                    secret.encode(), f"{event_id}.{timestamp}.".encode() + raw_body, hashlib.sha256
                ).digest()
            ).decode()
            valid = valid or hmac.compare_digest(expected, supplied)
    if not valid:
        raise ValueError("invalid signature")
    if event_id in seen_ids:
        return None
    seen_ids.add(event_id)
    return json.loads(raw_body)
