"""Slack request signature verification helpers."""

from __future__ import annotations

import hashlib
import hmac
import time


def verify_slack_signature(
    signing_secret: str,
    timestamp: str,
    body: bytes,
    signature: str,
) -> bool:
    if not signing_secret or not timestamp or not signature:
        return False

    try:
        ts_int = int(str(timestamp).strip())
    except Exception:
        return False

    # Replay protection: reject requests outside a five-minute skew window.
    if abs(int(time.time()) - ts_int) > 300:
        return False

    try:
        body_text = body.decode("utf-8")
    except Exception:
        body_text = body.decode("utf-8", errors="replace")

    base_string = f"v0:{timestamp}:{body_text}".encode("utf-8")
    computed = hmac.new(
        signing_secret.encode("utf-8"),
        base_string,
        hashlib.sha256,
    ).hexdigest()
    expected = f"v0={computed}"
    return hmac.compare_digest(expected, signature)


__all__ = ["verify_slack_signature"]
