"""velik.ai webhooks — signature verification (Python 3, standard library only).

X-Velik-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, f"{t}.{raw_body}")>
Verify over the RAW body bytes. Reject when |now - t| > 300 s. Compare in constant time.
"""
import hashlib
import hmac
import time


def verify_velik_signature(secret: str, header: str, raw_body: bytes, tolerance_sec: int = 300) -> dict:
    parts = {}
    for p in (header or "").split(","):
        k, _, v = p.strip().partition("=")
        if k == "t":
            parts["t"] = v
        elif k == "v1":
            parts.setdefault("v1", []).append(v)
    try:
        ts = int(parts.get("t", ""))
    except ValueError:
        return {"ok": False, "reason": "missing"}
    if "v1" not in parts:
        return {"ok": False, "reason": "missing"}
    if abs(int(time.time()) - ts) > tolerance_sec:
        return {"ok": False, "reason": "expired"}
    expected = hmac.new(secret.encode(), f"{ts}.".encode() + raw_body, hashlib.sha256).hexdigest()
    if any(hmac.compare_digest(v, expected) for v in parts["v1"]):
        return {"ok": True, "timestamp": ts}
    return {"ok": False, "reason": "mismatch"}


# Flask example:
# @app.post("/velik-webhook")
# def velik_webhook():
#     v = verify_velik_signature(os.environ["VELIK_WEBHOOK_SECRET"], request.headers.get("X-Velik-Signature"), request.get_data())
#     if not v["ok"]:
#         return v["reason"], 400
#     event = request.get_json()
#     if already_processed(event["id"]):   # at-least-once → dedupe on event.id
#         return "", 200
#     handle(event)
#     return "", 200

if __name__ == "__main__":
    import sys

    secret, header, path = sys.argv[1:4]
    tol = 10**12 if "--any-time" in sys.argv else 300
    with open(path, "rb") as f:
        print(verify_velik_signature(secret, header, f.read(), tol))
