import json
import os
import urllib.error
import urllib.request

QUESTION = {
    "type": "choice",
    "instructions": "Does the passage answer the question?",
    "criteria": {
        "yes": "The passage answers the question",
        "partly": "It answers only part of it",
        "no": "It does not answer it"
    }
}
BASE_URL = os.environ.get("DECISIO_BASE_URL", "http://127.0.0.1:8000").rstrip("/")
TIMEOUT = 15
REVIEW = "to a larger model or a person"


def route(text):
    request = urllib.request.Request(
        BASE_URL + "/v1/systemone",
        data=json.dumps({"state": text, "questions": {"answered": QUESTION}}).encode(),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
            answer = json.load(response)["answers"]["answered"]
        if not isinstance(answer, dict) or answer.get("type") != QUESTION["type"]:
            return REVIEW
        if not (answer.get("choice") in QUESTION["criteria"]):
            return REVIEW
        # A gold certificate is about correctness; agreement alone is insufficient.
        if (answer.get("certified") is True
                and answer.get("certificate_kind") == "gold"
                and isinstance(answer.get("certificate"), str)
                and answer["certificate"]):
            return {"yes": "answer from the passage", "partly": "answer, and say what is missing", "no": "say it is not in the documents"}[answer["choice"]]
        return "to a larger model or a person"
    except (urllib.error.URLError, TimeoutError, OSError, ValueError, KeyError, TypeError):
        return REVIEW


if __name__ == "__main__":
    print(route("Question: How long is the warranty?\nPassage: Every product comes with a two-year warranty from the date of purchase."))
