"""Validate a Sintonia webhook signature before parsing its JSON body."""
from __future__ import annotations

import base64
import hashlib
import hmac
import re
import time
from collections.abc import Mapping


def verify_webhook(
    raw_body: bytes,
    headers: Mapping[str, str],
    secret_base64: str,
    *,
    now: int | None = None,
    tolerance_seconds: int = 300,
) -> bool:
    headers = {name.lower(): value for name, value in headers.items()}
    timestamp = headers.get("x-sintonia-timestamp", "")
    signature = headers.get("x-sintonia-signature", "")
    if not re.fullmatch(r"[0-9]{1,12}", timestamp):
        return False
    if not re.fullmatch(r"v1=[0-9a-f]{64}", signature):
        return False
    current = int(time.time()) if now is None else now
    if tolerance_seconds < 0 or abs(current - int(timestamp)) > tolerance_seconds:
        return False
    try:
        key = base64.b64decode(secret_base64, validate=True)
    except (ValueError, TypeError):
        return False
    if len(key) != 32:
        return False
    signed = timestamp.encode("ascii") + b"." + raw_body
    expected = "v1=" + hmac.new(key, signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)
