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


ANSWERS = {
    "It is certain.": "An unequivocal yes.",
    "Outlook good.": "Likely yes, with a positive outlook.",
    "Signs point to yes.": "Tentatively yes, based on the available signs.",
    "Reply hazy, try again.": "The question is unclear or lacks enough context.",
    "Cannot predict now.": "The outcome is unknowable or depends on future events.",
    "Don't count on it.": "Probably not.",
    "My reply is no.": "A clear no.",
    "Very doubtful.": "Extremely unlikely.",
}


def ask(question, endpoint, deployment, api_key):
    body = {
        "model": deployment,
        "state": question,
        "questions": {
            "fortune": {
                "type": "choice",
                "instructions": (
                    "You are a playful Magic 8 Ball. Choose the most fitting "
                    "answer to the user's yes-or-no question. This is only "
                    "entertainment, not a real prediction."
                ),
                "criteria": ANSWERS,
            }
        },
    }
    request = urllib.request.Request(
        endpoint.rstrip("/") + "/providers/microsoft/v1/systemone",
        data=json.dumps(body).encode("utf-8"),
        headers={"Content-Type": "application/json", "api-key": api_key},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            payload = json.load(response)
    except urllib.error.HTTPError as exc:
        raise RuntimeError(f"Decision API returned HTTP {exc.code}.") from exc
    except (urllib.error.URLError, TimeoutError) as exc:
        raise RuntimeError("Could not reach the Decision API.") from exc
    except (ValueError, UnicodeDecodeError) as exc:
        raise RuntimeError("Decision API returned invalid JSON.") from exc

    try:
        answer = payload["answers"]["fortune"]
        choice = answer["choice"]
        if answer["type"] != "choice" or choice not in ANSWERS:
            raise ValueError
    except (KeyError, TypeError, ValueError) as exc:
        raise RuntimeError("Decision API returned an unexpected answer.") from exc
    return choice


def main():
    names = ("AZURE_ENDPOINT", "DEPLOYMENT_NAME", "AZURE_API_KEY")
    config = [os.environ.get(name, "").strip() for name in names]
    missing = [name for name, value in zip(names, config) if not value]
    if missing:
        print("Set these environment variables: " + ", ".join(missing), file=sys.stderr)
        return 1

    try:
        while True:
            if sys.stdin.isatty():
                print("Ask a yes/no question (Ctrl-D to exit): ", end="", file=sys.stderr, flush=True)
            line = sys.stdin.readline()
            if not line:
                return 0
            question = line.strip()
            if question:
                print(ask(question, *config), flush=True)
    except RuntimeError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        return 0


if __name__ == "__main__":
    sys.exit(main())
