import hashlib
import hmac
import time
from typing import Union


def verify_signature(
    secret: str,
    method: str,
    path: str,
    timestamp: str,
    request_id: str,
    body: Union[str, bytes],
    signature: str,
    tolerance_seconds: int = 300,
) -> bool:
    """Verify a PayFence HMAC signature from proxy mode."""
    try:
        ts = int(timestamp)
    except (ValueError, TypeError):
        return False

    if abs(time.time() - ts) > tolerance_seconds:
        return False

    if isinstance(body, str):
        body = body.encode()

    body_hash = hashlib.sha256(body).hexdigest()
    canonical = f"{method}\n{path}\n{timestamp}\n{request_id}\n{body_hash}"
    expected = hmac.new(secret.encode(), canonical.encode(), hashlib.sha256).hexdigest()

    return hmac.compare_digest(signature, expected)
