"""Python 3 : à exécuter sur votre serveur. Aucune bibliothèque à installer."""
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.request
from urllib.parse import urlsplit


def signer(payload, secret, timestamp=None):
    timestamp = str(int(time.time())) if timestamp is None else str(timestamp)
    body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    signature = hmac.new(
        secret.encode("utf-8"), timestamp.encode("ascii") + b"." + body, hashlib.sha256
    ).hexdigest()
    return body, {
        "Content-Type": "application/json",
        "X-AutoRelay-Timestamp": timestamp,
        "X-AutoRelay-Signature": "sha256=" + signature,
    }


class SansRedirection(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def envoyer():
    url = os.environ["AUTORELAY_WEBHOOK_URL"]
    secret = os.environ["AUTORELAY_SIGNING_SECRET"]
    event_id = os.environ["AUTORELAY_EVENT_ID"]
    if urlsplit(url).scheme != "https":
        raise ValueError("L’URL du webhook doit utiliser HTTPS.")
    body, headers = signer({
        "event_id": event_id,
        "event": "order.created",
        "shop_name": "Boutique de démonstration",
        "order_number": "CMD-DEMO-1042",
        "customer_name": "Client de démonstration",
        "product_name": "Sac Horizon",
        "amount": "35.00",
        "currency": "USD",
    }, secret)
    request = urllib.request.Request(url, data=body, headers=headers, method="POST")
    try:
        with urllib.request.build_opener(SansRedirection()).open(request, timeout=15) as response:
            print("HTTP", response.status, response.read().decode("utf-8"))
    except urllib.error.HTTPError as error:
        print("HTTP", error.code, error.read().decode("utf-8"))
        raise SystemExit(1)


if __name__ == "__main__":
    envoyer()
