"""GitHub webhook signature verification (HMAC-SHA256)."""
from __future__ import annotations
from typing import Optional

import hashlib
import hmac

from src.config import get_settings


def verify_github_signature(payload: bytes, signature_header: Optional[str]) -> bool:
    """Verify X-Hub-Signature-256 header against webhook secret.

    GitHub sends: sha256=<hex digest>
    We compute HMAC-SHA256 of the raw body with our webhook secret and compare.
    """
    if not signature_header:
        return False

    settings = get_settings()
    secret = settings.github_webhook_secret.encode("utf-8")

    if not secret:
        return False

    if not signature_header.startswith("sha256="):
        return False

    expected_sig = signature_header[7:]
    computed = hmac.new(secret, payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(computed, expected_sig)
