"""Security utilities for webhook signature verification."""

import hashlib
import hmac


def verify_signature(payload: bytes, signature: str, secret: str) -> bool:
    """
    Verify HMAC SHA256 signature of webhook payload.

    Args:
        payload: Raw request body as bytes
        signature: Signature from X-Gitea-Signature header
        secret: Webhook secret configured in Gitea

    Returns:
        True if signature is valid, False otherwise

    Example:
        >>> payload = b'{"action": "assigned"}'
        >>> secret = "my-webhook-secret"
        >>> sig = hmac.new(secret.encode(), payload, "sha256").hexdigest()
        >>> verify_signature(payload, sig, secret)
        True
    """
    if not signature:
        return False

    # Compute expected signature
    expected_signature = hmac.new(
        secret.encode("utf-8"), payload, hashlib.sha256
    ).hexdigest()

    # Use timing-safe comparison to prevent timing attacks
    return hmac.compare_digest(signature, expected_signature)
