"""Verify a Quantitizer delivery before acting on it.

Every webhook message carries

    Quantitizer-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>

Check it against the RAW request body (the exact bytes received, before any JSON
parsing), reject it when it does not match or when t is more than 5 minutes
from now, and drop an `id` you have already processed: a retry repeats it.

Usage in your handler:

    ok = verify(os.environ["QUANTITIZER_SECRET"], raw_body, request.headers["Quantitizer-Signature"])

Standard library only. Run as a script to check one saved message:
    QUANTITIZER_SECRET=qsk_... python3 verify.py body.json "t=...,v1=..."
"""

from __future__ import annotations

import hashlib
import hmac
import sys
import time


def verify(secret: str, raw_body: bytes | str, header: str, tolerance_s: int = 300, now: int | None = None) -> bool:
    if isinstance(raw_body, str):
        raw_body = raw_body.encode()
    parts = dict(p.strip().split("=", 1) for p in header.split(",") if "=" in p)
    try:
        t = int(parts["t"])
        given = bytes.fromhex(parts["v1"])
    except (KeyError, ValueError):
        return False
    if abs((now if now is not None else int(time.time())) - t) > tolerance_s:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).digest()
    return hmac.compare_digest(given, expected)


if __name__ == "__main__":
    import os

    body = open(sys.argv[1], "rb").read()
    now = int(os.environ["VERIFY_NOW"]) if os.environ.get("VERIFY_NOW") else None
    ok = verify(os.environ["QUANTITIZER_SECRET"], body, sys.argv[2], now=now)
    print("valid" if ok else "INVALID")
    sys.exit(0 if ok else 1)
