from __future__ import annotations

import hashlib
import hmac
import time

PREFIX = "sha256="
TOLERANCE = 300


class WebhookSignature:
    @staticmethod
    def verify(
        *,
        payload: str,
        secret: str,
        signature: str,
        timestamp: str | None = None,
        tolerance: int = TOLERANCE,
    ) -> bool:
        if not payload or not secret or not signature:
            return False
        if not signature.startswith(PREFIX):
            return False
        if _stale_timestamp(timestamp, tolerance):
            return False

        expected = PREFIX + hmac.new(
            secret.encode("utf-8"),
            payload.encode("utf-8"),
            hashlib.sha256,
        ).hexdigest()

        return hmac.compare_digest(expected, signature)


def _stale_timestamp(timestamp: str | None, tolerance: int) -> bool:
    if timestamp is None:
        return False
    try:
        ts = int(timestamp)
    except (ValueError, TypeError):
        return True
    return abs(int(time.time()) - ts) > tolerance
