# receiver.py: pip install flask, set ARCHITERA_WEBHOOK_SIGNING_SECRET
# Sandbox-only: verify signed fictional requests with the published test secret.
# Configured production HTTPS signing uses the same format with a private secret.
# Never use the public secret for real data or disable verification for production.
import base64, hashlib, hmac, json, os, time
from flask import Flask, request

secret = base64.b64decode(
    os.environ["ARCHITERA_WEBHOOK_SIGNING_SECRET"].removeprefix("whsec_")
)
seen = set()  # ephemeral deduplication for this synthetic exercise
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1_572_864  # the largest body read, 1.5 MiB; more gets 413


def verify(headers, raw_body):
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    if not msg_id or not timestamp or not timestamp.isascii() or not timestamp.isdigit():
        return False
    try:
        seconds = int(timestamp)
    except (ValueError, OverflowError):
        return False
    now = int(time.time())
    if seconds < now - 300 or seconds > now + 300:
        return False

    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    digest = hmac.digest(secret, signed, hashlib.sha256)
    expected = base64.b64encode(digest).decode()

    return any(
        value.startswith("v1,") and hmac.compare_digest(value[3:], expected)
        for value in headers.get("webhook-signature", "").split(" ")
    )


@app.post("/webhooks/architera")
def receive():
    raw_body = request.get_data()
    if not verify(request.headers, raw_body):
        return "", 401

    try:
        lead = json.loads(raw_body)
    except (ValueError, RecursionError):
        return "", 400
    if (
        not isinstance(lead, dict)
        or not isinstance(lead.get("event"), dict)
        or not isinstance(lead["event"].get("type"), str)
        or not isinstance(lead.get("customer"), dict)
        or not isinstance(lead["customer"].get("id"), str)
    ):
        return "", 400

    msg_id = request.headers["webhook-id"]
    if msg_id in seen:  # a retry or Replay: webhook-id is the stable event.id
        return "", 200
    seen.add(msg_id)
    print(lead["event"]["type"], lead["customer"]["id"])  # queue your work here
    return "", 204
