"""Oomplo API client for Python 3.9+: one file, the standard library only,
the documented API (docs/customer/api.md, docs/api.openapi.yaml). Copy it
into your project.

    from oomplo import Oomplo
    oomplo = Oomplo("https://oomplo.company.example", os.environ["OOMPLO_KEY"])
    pdf = oomplo.render("invoice-vat", {"client": {"name": "Contoso"}})
    open("invoice.pdf", "wb").write(pdf)
"""

import json
import time
import urllib.error
import urllib.parse
import urllib.request


class OomploError(Exception):
    """An answer of the API other than 2xx: its status and message."""

    def __init__(self, status, message, body=None):
        super().__init__(message)
        self.status = status
        self.body = body


class Oomplo:
    def __init__(self, base_url, api_key=None, timeout=300):
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key
        self.timeout = timeout

    def _call(self, path, body=None, headers=None):
        request = urllib.request.Request(
            self.base_url + path,
            data=None if body is None else json.dumps(body).encode("utf-8"),
            method="GET" if body is None else "POST",
        )
        if body is not None:
            request.add_header("Content-Type", "application/json")
        if self.api_key:
            request.add_header("Authorization", "Bearer " + self.api_key)
        for name, value in (headers or {}).items():
            request.add_header(name, value)
        try:
            with urllib.request.urlopen(request, timeout=self.timeout) as response:
                return response.read()
        except urllib.error.HTTPError as error:
            raw = error.read()
            try:
                answer = json.loads(raw)
            except ValueError:
                answer = None
            message = answer.get("error") if isinstance(answer, dict) else None
            raise OomploError(error.code, message or "HTTP %d" % error.code, answer) from None

    @staticmethod
    def _template(template):
        return urllib.parse.quote(template, safe="")

    def render(self, template, data, **options):
        """The PDF (or DOCX with format="docx") of a published template filled
        with data. Options: version, draft, strict, seal, missing ("error" or
        "empty"), format ("pdf" or "docx"), fields ("text" or "keep")."""
        return self._call("/api/templates/%s/render" % self._template(template), dict(options, data=data))

    def schema(self, template, version=None):
        """What data a template needs: fields, arrays, example, jsonSchema."""
        query = "?version=%d" % version if version else ""
        return json.loads(self._call("/api/templates/%s/schema%s" % (self._template(template), query)))

    def validate(self, template, data, version=None):
        """Every problem of data for a template, without a PDF."""
        body = {"data": data}
        if version:
            body["version"] = version
        return json.loads(self._call("/api/templates/%s/validate" % self._template(template), body))

    def start_job(self, template, name, rows, key=None, **options):
        """A series job of rows (one document each, the source name replaced
        by a row); with key a repeated call returns the same job. Options:
        zip, label, webhook, output (a path in the client's store for the
        result), format, fields, missing, version, strict, seal."""
        body = dict(options, series={"name": name, "rows": rows})
        headers = {"Idempotency-Key": key} if key else None
        return json.loads(self._call("/api/templates/%s/jobs" % self._template(template), body, headers))

    def job(self, job_id):
        return json.loads(self._call("/api/jobs/%s" % urllib.parse.quote(job_id, safe="")))

    def job_result(self, job_id, poll=0.5, timeout=600):
        """Wait for a job and return its result (a ZIP or one PDF)."""
        until = time.monotonic() + timeout
        while True:
            state = self.job(job_id)
            if state["state"] == "done":
                break
            if state["state"] == "failed":
                raise OomploError(422, state.get("error") or "The job failed.", state)
            if time.monotonic() > until:
                raise OomploError(408, "The job takes longer than the time limit.", state)
            time.sleep(poll)
        return self._call("/api/jobs/%s/result" % urllib.parse.quote(job_id, safe=""))
