"""Python 3.8+ standard-library civil diagnostics client; no device control."""
import json
import urllib.parse
import urllib.request


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise ValueError("Redirect refused")


class DiagnosticsClient:
    def __init__(self, base_url="https://metamorphosesystems.com"):
        url = urllib.parse.urlsplit(base_url)
        if url.scheme != "https" and not (url.scheme == "http" and url.hostname in {"localhost", "127.0.0.1"}):
            raise ValueError("HTTPS required")
        if url.username or url.password or url.query or url.fragment:
            raise ValueError("Use a clean origin, without credentials")
        self.origin = "{}://{}".format(url.scheme, url.netloc)

    def normalize(self, records):
        request = urllib.request.Request(self.origin + "/api/public/integration/normalize",
            data=json.dumps({"records": records}, allow_nan=False).encode(),
            headers={"Content-Type": "application/json"}, method="POST")
        with urllib.request.build_opener(NoRedirect()).open(request, timeout=10) as response:
            return json.load(response)