import hashlib, hmac, os, time
_seen: dict[str,float] = {}

def verify(timestamp: str, body: bytes, signature: str) -> bool:
    secret = os.getenv("TRADING_AI_SHARED_SECRET", "")
    if not secret or not timestamp or abs(time.time()-int(timestamp)) > 60: return False
    expected = hmac.new(secret.encode(), timestamp.encode()+b"."+body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature) or signature in _seen: return False
    now=time.time()
    for key,seen_at in list(_seen.items()):
        if now-seen_at>60: _seen.pop(key,None)
    _seen[signature]=now
    return True
