"""Python 3.10+. Standard library only. Read-only unless explicitly enabled."""
import json
import os
from urllib.request import Request, urlopen
from urllib.parse import quote
from urllib.error import HTTPError

BASE = 'https://torok-api.onrender.com/api/integrations/v1'
KEY = os.environ['MASSAR_API_KEY']

def api(path, method='GET', body=None):
    req = Request(BASE + path, method=method,
                  headers={'Authorization': 'Bearer ' + KEY, 'Content-Type': 'application/json'},
                  data=None if body is None else json.dumps(body).encode())
    try:
        with urlopen(req, timeout=20) as response:
            text = response.read().decode()
            return json.loads(text) if text else None
    except HTTPError as error:
        detail = error.read().decode()
        raise RuntimeError(f'Massar HTTP {error.code}: {detail}; Retry-After={error.headers.get("Retry-After")}') from None

print(json.dumps(api('/cities?q=' + quote(os.getenv('MASSAR_CITY_QUERY', 'Nasr'), safe='')), ensure_ascii=False, indent=2))
if os.getenv('MASSAR_CITY_ID'):
    print(api('/quote', 'POST', {'cityId': os.environ['MASSAR_CITY_ID'], 'productCodAmount': 1000, 'paymentMethod': 'COD'}))
if os.getenv('MASSAR_CREATE_ORDER') == 'YES':
    # Creates a real shipment. Reuse the exact saved payload and externalOrderId on retry.
    with open(os.getenv('MASSAR_ORDER_FILE', 'order.json')) as source:
        print(api('/orders', 'POST', json.load(source)))
if os.getenv('MASSAR_EXTERNAL_ORDER_ID'):
    print(api('/orders/' + quote(os.environ['MASSAR_EXTERNAL_ORDER_ID'], safe='')))
