#!/usr/bin/env python3
"""/mancgi/snapexpayresult: SnapEX Pay webhook. Signed; the invoice state is re-read from the API before crediting."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "lib", "python"))

import snapexpay  # noqa: E402
from snapexpay import gateway, web  # noqa: E402

if os.environ.get("REQUEST_METHOD", "GET").upper() != "POST":
    web.respond(200, "SnapEX Pay webhook endpoint")
    sys.exit(0)
try:
    status, text = gateway.webhook(web.body(), web.headers())
except Exception as err:
    snapexpay.logger().exception("webhook: %s", err)
    status, text = 500, "error"  # SnapEX retries
if status != 200:
    snapexpay.logger().warning("webhook answered %d: %s", status, text)
web.respond(status, text)
