"""A small Piggy client in plain Python (3.9+, standard library only).

    from piggy_client import Piggy
    piggy = Piggy("https://127.0.0.1:8379", key_file="~/.myapp/piggy-key",
                  certificate="~/.myapp/piggy-cert.pem")
    answer = piggy.infer("Say hello in five words.", model="haiku")

Copy it into your app and change what you need. Run it directly to try a
connection:

    python3 piggy_client.py BASE_URL KEY_FILE [CERTIFICATE_FILE]
"""
import json
import os
import ssl
import sys
import time
import urllib.error
import urllib.request

# Seconds to wait before retrying, by status (0: no answer at all, for example a
# dropped connection). 400 and 401 are never retried; 429 means come back in minutes.
RETRY_AFTER_S = {0: 5, 500: 5, 502: 30, 503: 3, 504: 5}


def _json(raw):
    try:
        return json.loads(raw)
    except ValueError:
        return {"error": raw.decode(errors="replace")[:200] or "an empty answer"}


class PiggyError(Exception):
    def __init__(self, status, body):
        super().__init__(f"Piggy answered {status}: {body.get('error')}")
        self.status, self.body = status, body


class Piggy:
    def __init__(self, base_url, key_file, certificate=None):
        self.base_url = base_url.rstrip("/")
        with open(os.path.expanduser(key_file)) as f:
            self._key = f.read().strip()
        self._context = None
        if self.base_url.startswith("https://"):
            if not certificate:
                raise ValueError("an https address needs Piggy's certificate file")
            # trust exactly the certificate this Piggy made
            self._context = ssl.create_default_context(cafile=os.path.expanduser(certificate))
        elif certificate:
            raise ValueError("a certificate is only for an https address")

    def _call(self, method, path, body=None, timeout_s=35):
        headers = {"Authorization": f"Bearer {self._key}"}
        data = None
        if body is not None:
            headers["Content-Type"] = "application/json"
            data = json.dumps(body).encode()
        request = urllib.request.Request(self.base_url + path, data=data, headers=headers, method=method)
        try:
            with urllib.request.urlopen(request, timeout=timeout_s, context=self._context) as response:
                return response.status, _json(response.read())
        except urllib.error.HTTPError as error:
            return error.code, _json(error.read())
        except (urllib.error.URLError, OSError) as error:   # refused, dropped, timed out, TLS
            return 0, {"error": f"no answer from Piggy: {getattr(error, 'reason', error)}"}

    def health(self):
        status, body = self._call("GET", "/health", timeout_s=5)
        if status != 200:
            raise PiggyError(status, body)
        return body

    def infer(self, prompt, model, schema=None, system=None, timeout_s=30, attempts=3):
        """The answer: an object when you sent a schema, else text."""
        body = {"prompt": prompt, "model": model, "timeout_s": timeout_s}
        if schema is not None:
            body["schema"] = schema
        if system is not None:
            body["system"] = system
        for attempt in range(1, attempts + 1):
            status, answer = self._call("POST", "/infer", body, timeout_s=timeout_s + 5)
            if status == 200:
                if schema is not None and not answer["structured"]:
                    raise PiggyError(status, {"error": "the answer did not match the schema"})
                return answer["output"]
            if status not in RETRY_AFTER_S or attempt == attempts:
                raise PiggyError(status, answer)
            time.sleep(RETRY_AFTER_S[status] * attempt)

    # --- jobs ---------------------------------------------------------------

    def start_job(self, prompt, model, profile, system=None, max_runtime_s=None):
        body = {"prompt": prompt, "model": model, "profile": profile}
        if system is not None:
            body["system"] = system
        if max_runtime_s is not None:
            body["max_runtime_s"] = max_runtime_s
        status, answer = self._call("POST", "/v2/jobs", body)
        if status != 202:
            raise PiggyError(status, answer)
        return answer["job_id"]

    def job(self, job_id):
        status, answer = self._call("GET", f"/v2/jobs/{job_id}")
        if status != 200:
            raise PiggyError(status, answer)
        return answer

    def wait_for_job(self, job_id, poll_s=3, limit_s=3600):
        deadline = time.time() + limit_s
        while True:
            job = self.job(job_id)
            if job["status"] in ("succeeded", "failed", "timed_out", "cancelled"):
                return job
            if time.time() >= deadline:
                raise TimeoutError(f"job {job_id} still {job['status']} after {limit_s} s")
            time.sleep(poll_s)

    def transcript(self, job_id):
        status, answer = self._call("GET", f"/v2/jobs/{job_id}/transcript")
        if status != 200:
            raise PiggyError(status, answer)
        return answer["entries"]

    def cancel_job(self, job_id):
        status, answer = self._call("POST", f"/v2/jobs/{job_id}/cancel")
        if status not in (202, 409):          # 409: it had already ended
            raise PiggyError(status, answer)
        return answer


if __name__ == "__main__":
    if len(sys.argv) < 3:
        sys.exit(__doc__)
    piggy = Piggy(sys.argv[1], sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else None)
    print("Piggy", piggy.health()["version"])
    print(piggy.infer("Is the sky blue on a clear day? Answer yes or no.", model="haiku",
                      schema={"type": "object", "properties": {"answer": {"type": "string", "enum": ["yes", "no"]}},
                              "required": ["answer"]}))
