"""Vozira API example. Read-only when run; never automatically retries mutations."""
import json, os, urllib.request, urllib.error
BASE = "https://vozirasms.com/api/v1"
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None
OPENER = urllib.request.build_opener(NoRedirect())
def request(path, method="GET", body=None, idempotency_key=None):
    if not path.startswith("/") or path.startswith("//"):
        raise ValueError("Use a relative Vozira API path")
    headers = {"X-Api-Key": os.environ["VOZIRA_API_KEY"], "Content-Type": "application/json"}
    if idempotency_key: headers["Idempotency-Key"] = idempotency_key
    req = urllib.request.Request(BASE + path, data=None if body is None else json.dumps(body).encode(), headers=headers, method=method)
    try:
        with OPENER.open(req, timeout=30) as response:
            return response.status, json.load(response)
    except urllib.error.HTTPError as error:
        payload = error.read()
        try: data = json.loads(payload)
        except (ValueError, UnicodeDecodeError): data = {"error": {"code": "NON_JSON_RESPONSE"}}
        return error.code, data
    # Timeouts are intentionally not retried. Query the original saved key.
if __name__ == "__main__":
    print(request("/balance"))
