"""Synthetic signature check, not a complete webhook endpoint.

Contract source: https://developers.intercom.com/docs/references/webhooks/webhook-models
Intercom's documented notification scheme uses HMAC-SHA1 over original body bytes.
Use the real app secret from a protected server store, never a request parameter.
Run: python3 intercom_signature.py
"""
import hashlib
import hmac


def valid_signature(raw_body: bytes, signature: str | None, app_secret: bytes) -> bool:
    if not signature or not app_secret:
        return False
    expected = 'sha1=' + hmac.new(app_secret, raw_body, hashlib.sha1).hexdigest()
    return hmac.compare_digest(expected.encode('ascii'), signature.encode('utf-8'))


if __name__ == '__main__':
    secret = b'SYNTHETIC-LOCAL-TEST-SECRET'
    body = b'{"id":"EVENT-1","topic":"conversation.user.replied"}'
    signature = 'sha1=' + hmac.new(secret, body, hashlib.sha1).hexdigest()
    assert valid_signature(body, signature, secret)
    assert not valid_signature(body + b' ', signature, secret)
    assert not valid_signature(body, None, secret)
    assert not valid_signature(body, signature, b'DIFFERENT-TEST-SECRET')
    assert not valid_signature(body, 'sha1=not-a-valid-digest', secret)
    print('Passed 5 signature checks. No endpoint or network request was used.')
