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

POLICY = {
    "inspect": "allow",
    "git_read": "allow",
    "git_local_write": "allow",
    "git_discard": "ask",
    "git_push": "ask",
    "git_push_force_or_protected": "block",
    "test_build_lint": "allow",
    "run_scripts": "ask",
    "install_packages": "ask",
    "edit_workspace": "allow",
    "delete_in_workspace": "ask",
    "outside_workspace": "block",
    "secrets": "block",
    "network_and_cloud": "ask",
    "remote_code_or_privilege": "block",
    "other": "ask",
}

QUESTION = {
    "type": "choice",
    "instructions": "Which of the team's rules covers this shell command?",
    "criteria": {
        "inspect": None,
        "git_read": None,
        "git_local_write": None,
        "git_discard": None,
        "git_push": None,
        "git_push_force_or_protected": None,
        "test_build_lint": None,
        "run_scripts": None,
        "install_packages": None,
        "edit_workspace": None,
        "delete_in_workspace": None,
        "outside_workspace": None,
        "secrets": None,
        "network_and_cloud": None,
        "remote_code_or_privilege": None,
        "other": None
    }
}
BASE_URL = os.environ.get("DECISIO_BASE_URL", "http://127.0.0.1:8000").rstrip("/")
TIMEOUT = 15
REVIEW = "ask"


def route(text):
    request = urllib.request.Request(
        BASE_URL + "/v1/systemone",
        data=json.dumps({"state": text, "questions": {"rule": QUESTION}}).encode(),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
            answer = json.load(response)["answers"]["rule"]
        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 POLICY[answer["choice"]]
        return "ask"
    except (urllib.error.URLError, TimeoutError, OSError, ValueError, KeyError, TypeError):
        return REVIEW


if __name__ == "__main__":
    print(route("rm -rf build/ && npm run build"))
