"""Inbound webhook token minting and HMAC signature verification (build plan 8.2)."""

from __future__ import annotations

import hashlib
import hmac
import secrets


def mint_webhook_credentials() -> tuple[str, str]:
    """Return a (token, secret) pair for a workflow's inbound webhook URL."""
    return secrets.token_urlsafe(24), secrets.token_urlsafe(32)


def sign(secret: str, body: bytes) -> str:
    """Compute the hex HMAC-SHA256 signature for a raw request body."""
    return hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()


def verify_signature(secret: str, body: bytes, provided: str | None) -> bool:
    if not provided:
        return False
    expected = sign(secret, body)
    # Accept an optional "sha256=" prefix (common webhook convention).
    candidate = provided.split("=", 1)[1] if provided.startswith("sha256=") else provided
    return hmac.compare_digest(expected, candidate)
