#!/usr/bin/env python3
"""Social Media Guru Pay — Python 3 server example.

    export SMG_SECRET=sk_live_…
    python3 examples/server.py
"""
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.request

SMG_BASE = os.environ.get("SMG_BASE", "https://www.socialmediaguru.co.za")
SECRET = os.environ.get("SMG_SECRET", "sk_live_YOUR_SECRET")
WEBHOOK_SECRET = os.environ.get("SMG_WEBHOOK_SECRET", "whsec_YOUR_WEBHOOK_SECRET")


def smg_request(method, path, body=None):
    data = None if body is None else json.dumps(body).encode("utf-8")
    req = urllib.request.Request(
        SMG_BASE + path,
        data=data,
        method=method,
        headers={
            "Authorization": "Bearer " + SECRET,
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=20) as res:
            return json.loads(res.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        raw = e.read().decode("utf-8", "replace")
        try:
            err = json.loads(raw).get("error", raw)
        except ValueError:
            err = raw
        raise RuntimeError("%s (HTTP %s)" % (err, e.code))


def smg_create_payment(amount, merchant_ref, customer, return_url, cancel_url=""):
    res = smg_request(
        "POST",
        "/api/v1/payments",
        {
            "amount": amount,
            "merchant_ref": merchant_ref,
            "customer": customer,
            "return_url": return_url,
            "cancel_url": cancel_url,
        },
    )
    return res["data"]


def smg_verify_webhook(raw_body, signature_header):
    expected = hmac.new(
        WEBHOOK_SECRET.encode("utf-8"),
        raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(expected, signature_header or "")


if __name__ == "__main__":
    payment = smg_create_payment(
        199.0,
        "ORD-%s" % int(time.time()),
        {"name": "Jane Doe", "email": "jane@example.com", "phone": "0713743360"},
        "https://yourstore.co.za/thanks",
    )
    print("Pass payment_url to SmgPay.open():", payment["payment_url"])
