#!/usr/bin/env python3
"""Madely quickstart (Python, standard library only). Sandbox: nothing is printed, shipped or charged.
Usage: MADELY_BASE=https://api.madely.ai python3 quickstart.py"""
import json, os, urllib.request, urllib.error

BASE = os.environ.get("MADELY_BASE", "https://api.madely.ai")


def call(method, path, body=None, key=None, idem=None):
    headers = {"Accept": "application/json"}
    if body is not None:
        headers["Content-Type"] = "application/json"
    if key:
        headers["Authorization"] = f"Bearer {key}"
    if idem:
        headers["Idempotency-Key"] = idem
    req = urllib.request.Request(BASE + path, method=method, headers=headers,
                                 data=json.dumps(body).encode() if body is not None else None)
    try:
        with urllib.request.urlopen(req) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        err = json.load(e).get("error", {})
        # Errors say what is wrong and how to fix it: read hint, fix `param`, retry only if retryable.
        raise SystemExit(f"{e.code} {err.get('code')}: {err.get('message')} | hint: {err.get('hint')} | retryable={err.get('retryable')}")


product = call("GET", "/v1/products?q=mug&limit=1")["products"][0]            # 1 discover + find
print("product", product["product_id"], f"${product['price_usd']}")
key = call("POST", "/v1/sandbox/keys")["api_key"]                               # 2 sandbox key, no signup
spec = call("GET", "/v1/products/K04/print-spec")                               # 3 print spec
print("canvas", spec["canvas_px"], "dpi", spec["dpi"])
check = call("POST", "/v1/print-spec/validate", {"product_id": "K04", "width_px": 2550, "height_px": 1155,
                                                  "format": "png", "has_transparency": False})  # 4 validate
print("valid", check["valid"])
quote = call("POST", "/v1/quotes", {"items": [{"product_id": "K04", "quantity": 24}],
                                    "ship_to": {"country": "US", "zip": "80202"}})  # 5 quote
call("POST", "/v1/payment-methods", {"payment_method_id": "pm_card_visa"}, key=key)  # sandbox test card
order = call("POST", "/v1/orders", {                                            # 6 test order
    "quote_id": quote["quote_id"], "external_id": f"madely-smoketest-py-{os.getpid()}", "submit": True,
    "payment": {"method": "card_on_file"},
    "ship_to": {"name": "Test Buyer", "address1": "1 Test St", "city": "Denver", "state": "CO", "zip": "80202", "country": "US"},
    "items": [{"product_id": "K04", "quantity": 24,
               "artwork": [{"placement": "wrap", "url": "https://example.com/art/mug.png", "width_px": 2550, "height_px": 1155}]}],
}, key=key, idem=f"madely-smoketest-py-{os.getpid()}")
status = call("GET", f"/v1/orders/{order['order_id']}", key=key)               # 7 status
print("order", order["order_id"], status["status"], f"total=${status['total_usd']}")
