#!/usr/bin/env python3
"""Proposed webhook signing profile demonstration. Synthetic data only.
This is an HTTP integration example, not a released Trusted Records SDK.
The real signature algorithm/window/key-rotation policy must be agreed.
Replay state must be transactional and persistent in a real receiver.
"""
import hashlib,hmac,json,time
def verify(raw_body:bytes,timestamp:str,signature:str,secret:bytes,now:int,window:int,seen:set):
    try:stamp=int(timestamp)
    except ValueError:return 'BAD_TIMESTAMP'
    if abs(now-stamp)>window:return 'STALE'
    expected=hmac.new(secret,timestamp.encode()+b'.'+raw_body,hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected,signature):return 'BAD_SIGNATURE'
    try:event=json.loads(raw_body)
    except (ValueError,UnicodeDecodeError):return 'BAD_BODY'
    required={'eventId','eventType','occurredAt','tenantId','projectId','objectRef','version','correlationId'}
    if not isinstance(event,dict) or not required.issubset(event):return 'BAD_ENVELOPE'
    event_id=event['eventId']
    if event_id in seen:return 'DUPLICATE'
    # Receiver additionally checks expected tenant/project/object version.
    seen.add(event_id)
    return 'VERIFIED_SYNTHETIC'
if __name__=='__main__':
    now=int(time.time());stamp=str(now);secret=b'synthetic-example-not-a-production-secret'
    body=json.dumps(dict(eventId='synthetic-event-001',eventType='records.declared',occurredAt='2026-10-07T00:00:00Z',tenantId='synthetic-tenant-001',projectId='synthetic-project-001',objectRef='synthetic-record-001',version=1,correlationId='synthetic-correlation-001'),separators=(',',':')).encode()
    sig=hmac.new(secret,stamp.encode()+b'.'+body,hashlib.sha256).hexdigest();seen=set()
    assert verify(body,stamp,sig,secret,now,300,seen)=='VERIFIED_SYNTHETIC'
    assert verify(body,stamp,sig,secret,now,300,seen)=='DUPLICATE'
    assert verify(body+b' ',stamp,sig,secret,now,300,set())=='BAD_SIGNATURE'
    assert verify(body,str(now-1000),sig,secret,now,300,set())=='STALE'
    print('Synthetic signature, tamper, expiry and duplicate checks passed.')
