import hashlib
import hmac
import logging
import time
from typing import Union

logger = logging.getLogger("payfence")


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):
        logger.info("HMAC rejected: invalid timestamp '%s'", timestamp)
        return False

    age = abs(time.time() - ts)
    if age > tolerance_seconds:
        logger.info("HMAC rejected: timestamp expired (age=%ds, tolerance=%ds)", int(age), 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()

    valid = hmac.compare_digest(signature, expected)
    if valid:
        logger.debug("HMAC verified: %s %s", method, path)
    else:
        logger.info("HMAC rejected: signature mismatch for %s %s", method, path)
    return valid
