#!/usr/bin/env python3
"""/mancgi/snapexpayreturn?elid=<payment>: SnapEX Pay sends the client back here; credit at once if the money is in."""

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 billmgr, gateway, web  # noqa: E402

payment_id = web.int_param(web.query(), "elid")
manager_url = web.site() + "/billmgr"
try:
    paid, url = gateway.returned(payment_id)
    manager_url = url or manager_url
    if paid:
        web.redirect(billmgr.page(manager_url, "payment.success", payment_id))
    else:
        web.page(200, "Thank you! Your payment is being confirmed on the blockchain. The balance is credited"
                      " automatically, usually within a few minutes - you can close this page.",
                 manager_url + "?func=payment", "Back to payments")
except gateway.UserError as err:
    web.page(404, str(err), manager_url)
except Exception as err:
    snapexpay.logger().exception("return %d: %s", payment_id, err)
    web.page(200, "Your payment is being confirmed. The balance is credited automatically once it arrives.",
             manager_url + "?func=payment", "Back to payments")
