"""Python 3.10+ backend example, not a published Zwipe SDK. No dependencies."""
import json
import time
from http.client import HTTPException
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class ZwipeError(Exception):
    def __init__(self, message, *, code, status=0, request_id=None):
        super().__init__(message)
        self.code = code
        self.status = status
        self.request_id = request_id


class _NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


class ZwipeClient:
    """Use one instance per worker; this minimal example is not thread-safe."""
    def __init__(self, client_id, client_secret, base_url="https://api.zwipe.co", timeout=15):
        url = urlsplit(base_url)
        local = url.hostname in ("localhost", "127.0.0.1", "::1")
        if (not url.hostname or url.username or url.password or url.query or url.fragment
                or url.path not in ("", "/")
                or (url.scheme != "https" and not (url.scheme == "http" and local))):
            raise ValueError("Use an HTTPS origin; HTTP is for local mocks only")
        if not client_id or not client_secret:
            raise ValueError("Server credentials are required")
        self._credentials = {"client_id": client_id, "client_secret": client_secret}
        self._base = base_url.rstrip("/")
        self._timeout = timeout
        self._opener = build_opener(_NoRedirect())
        self._token = None
        self._expires_at = 0

    def _send(self, path, method="GET", body=None, token=None):
        headers = {"Accept": "application/json"}
        if token:
            headers["Authorization"] = "Bearer " + token
        data = None
        if body is not None:
            headers["Content-Type"] = "application/json"
            data = json.dumps(body).encode("utf-8")
        request = Request(self._base + path, data=data, headers=headers, method=method)
        try:
            response = self._opener.open(request, timeout=self._timeout)
        except HTTPError as error:
            response = error
        except (URLError, TimeoutError, OSError, HTTPException) as error:
            raise ZwipeError("No complete response; preserve the order reference.",
                             code="transport_error") from error
        with response:
            request_id = response.headers.get("X-Request-Id")
            try:
                result = json.loads(response.read())
            except (TimeoutError, OSError, HTTPException) as error:
                raise ZwipeError("Response interrupted; preserve the order reference.",
                                 code="transport_error") from error
            except (ValueError, UnicodeError) as error:
                raise ZwipeError("Unreadable API response.", code="invalid_response",
                                 status=response.status, request_id=request_id) from error
            if not isinstance(result, dict):
                raise ZwipeError("Expected a JSON object.", code="invalid_response",
                                 status=response.status, request_id=request_id)
            if response.status >= 300:
                details = result.get("error") or {}
                raise ZwipeError(details.get("message", "Zwipe request failed."),
                                 code=details.get("code", "http_error"),
                                 status=response.status, request_id=request_id)
            return result

    def _access_token(self):
        if self._token and time.monotonic() < self._expires_at:
            return self._token
        started = time.monotonic()
        result = self._send("/v1/auth/token", "POST", self._credentials)
        token, expires = result.get("access_token"), result.get("expires_in")
        if not isinstance(token, str) or not token or not isinstance(expires, (int, float)) or expires <= 0:
            raise ZwipeError("Invalid token response.", code="invalid_response")
        self._token = token
        self._expires_at = started + max(0, expires - 60)
        return token

    def request(self, path, method="GET", body=None):
        if not path.startswith("/v1/") or "?" in path or "#" in path:
            raise ValueError("Use a /v1/ path without a query string or fragment")
        token = self._access_token()
        try:
            return self._send(path, method, body, token)
        except ZwipeError as error:
            if error.status != 401:
                raise  # Never automatically replay transport failures or 5xx responses.
            self._token = None
            return self._send(path, method, body, self._access_token())

    def get_card(self, card_id):
        return self.request("/v1/cards/" + quote(card_id, safe=""))

    def get_balance(self, card_id):
        return self.request("/v1/cards/" + quote(card_id, safe="") + "/balance")

    def issue_card(self, persisted_order):
        return self.request("/v1/cards", "POST", persisted_order)
