"""Bitbucket webhook HMAC verification."""
from __future__ import annotations

import hashlib
import hmac
from typing import Optional

from src.config import get_settings


def verify_bitbucket_user_webhook_signature(
    payload: bytes,
    signature_header: Optional[str],
) -> bool:
    secret = (get_settings().bitbucket_user_webhook_secret or "").strip()
    if not secret:
        return False
    if not signature_header or "=" not in signature_header:
        return False
    method, given = signature_header.split("=", 1)
    method = method.strip().lower()
    if method != "sha256" or not given.strip():
        return False
    expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature_header.strip())
