"""
Veritus webhook receiver — reference implementation (Python / Flask).

Verifies the HMAC-SHA256 signature, then acts on verdict.overridden to
release a held signup. Adapt the marked TODO to your own user store.

Secret: the signing secret shown once when you created the webhook
(Forms -> your site -> Webhooks, or /dashboard/webhooks).
"""
import hmac, hashlib, os, json
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = (os.environ.get("VERITUS_WEBHOOK_SECRET") or "whsec_PUT_YOURS_HERE").encode()


@app.post("/veritus/webhook")
def veritus_webhook():
    # 1. Verify signature over the RAW body (not request.json).
    raw = request.get_data()
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    given = request.headers.get("X-Veritus-Signature", "")
    if not hmac.compare_digest(expected, given):
        abort(401)

    # 2. Parse and dispatch.
    body = json.loads(raw or b"{}")
    data = body.get("data", {})
    if body.get("event") == "verdict.overridden":
        email = str(data.get("email", "")).lower().strip()
        verdict = str(data.get("new_verdict", "")).lower().strip()
        if email and verdict == "allow":
            # ─── TODO: activate this user's account in your own system ───
            # db.execute("UPDATE users SET verified='yes' WHERE lower(email)=%s", [email])
            # ─────────────────────────────────────────────────────────────
            pass
        # 'block'/'review' -> leave held.

    # 3. Return 2xx fast.
    return "", 200
