"""
Slack request signature verification.

slack-bolt's AsyncApp handles signature verification automatically when
initialized with a signing_secret. This module provides a standalone
helper for contexts that require manual verification (e.g., testing,
custom middleware layers).

In production, prefer slack-bolt's built-in verification — do NOT disable
it or bypass it.
"""

from __future__ import annotations

import hashlib
import hmac
import time


def verify_slack_signature(
    body: bytes,
    timestamp: str,
    signature: str,
    signing_secret: str,
    max_age_seconds: int = 300,
) -> bool:
    """
    Verify a Slack webhook request signature.

    Implements Slack's signing secret verification algorithm:
    https://api.slack.com/authentication/verifying-requests-from-slack

    Args:
        body:            Raw request body bytes.
        timestamp:       Value of the ``X-Slack-Request-Timestamp`` header.
        signature:       Value of the ``X-Slack-Signature`` header.
        signing_secret:  App's signing secret from Slack dashboard.
        max_age_seconds: Reject requests older than this (replay protection).

    Returns:
        True if signature is valid and request is fresh, False otherwise.
    """
    # Replay attack prevention — reject stale requests
    try:
        request_age = abs(int(time.time()) - int(timestamp))
    except (ValueError, TypeError):
        return False

    if request_age > max_age_seconds:
        return False

    # Compute expected signature
    sig_basestring = f"v0:{timestamp}:{body.decode('utf-8', errors='replace')}"
    computed = (
        "v0="
        + hmac.new(
            signing_secret.encode("utf-8"),
            sig_basestring.encode("utf-8"),
            hashlib.sha256,
        ).hexdigest()
    )

    # Constant-time comparison to prevent timing attacks
    return hmac.compare_digest(computed, signature)
