"""Educational Jev example. Fixture by default; --live makes a billed API call."""
import argparse
import json
import math
import os
import urllib.request
import urllib.error
from copy import deepcopy

STATE = {'message': 'Invoice contact: billing@example.com. My personal email is sam@example.net.', 'candidates': {'candidate_0': 'billing@example.com', 'candidate_1': 'sam@example.net'}}
QUESTIONS = {'billing_email': {'type': 'choice', 'instructions': 'Which candidate is the invoice contact email? Return none if it is absent.', 'criteria': {'candidate_0': 'billing@example.com', 'candidate_1': 'sam@example.net', 'none': 'No invoice contact among candidates'}}}
FIXTURE = {'billing_email': {'type': 'choice', 'choice': 'candidate_0', 'confidence': 0.96, 'probabilities': {'candidate_0': 0.9733333333333334, 'candidate_1': 0.013333333333333308, 'none': 0.013333333333333308}}}

import re
candidates = list(dict.fromkeys(re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", STATE["message"])))
if len(candidates) > 254:
    raise ValueError("Too many candidates; partition or review")
STATE["candidates"] = {"candidate_" + str(i): value for i, value in enumerate(candidates)}
QUESTIONS["billing_email"]["criteria"] = {**STATE["candidates"], "none": "No invoice contact among candidates"}

def decide(answers, state):
    answer = answers["billing_email"]
    if answer["confidence"] < .9 or answer["choice"] == "none":
        return {"route": "review", "value": None}
    selected = state["candidates"].get(answer["choice"])
    if selected is None:
        return {"route": "invalid_candidate", "value": None}
    local, domain = selected.rsplit("@", 1)
    return {"route": "selected", "value": local + "@" + domain.lower(),
            "deliverability_verified": False}

def validate(answers):
    if not isinstance(answers, dict):
        raise ValueError("Answer map missing")
    for name, question in QUESTIONS.items():
        answer = answers.get(name)
        if not isinstance(answer, dict) or answer.get("type") != question["type"]:
            raise ValueError("Missing or unexpected answer type: " + name)
        field = {"choice": "choice", "score": "score", "noul": "noul"}[question["type"]]
        value = answer.get(field)
        if field == "choice":
            if value not in question["criteria"]:
                raise ValueError("Unknown category: " + name)
        elif not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(value):
            raise ValueError("Invalid number: " + name)
        elif not 0 <= value <= (1 if field == "noul" else len(question["criteria"])-1):
            raise ValueError("Out-of-range answer: " + name)
        if field != "noul":
            c = answer.get("confidence")
            if not isinstance(c, (int, float)) or isinstance(c, bool) or not math.isfinite(c) or not 0 <= c <= 1:
                raise ValueError("Invalid confidence: " + name)
    return answers

def evaluate(live=False):
    if not live:
        return {"model": "fixture-not-a-model-run", "answers": deepcopy(FIXTURE)}
    key = os.environ.get("TYPESAFE_API_KEY", "").strip()
    if not key:
        raise ValueError("Set TYPESAFE_API_KEY in the environment for --live")
    payload = {"model": "jev-1.13.0", "state": STATE, "questions": QUESTIONS}
    request = urllib.request.Request("https://api.typesafe.ai/v1/systemone",
        data=json.dumps(payload).encode(), method="POST",
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
    # A bounded single call. The application can add a bounded retry policy.
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--live", action="store_true")
    args = parser.parse_args()
    try:
        result = evaluate(args.live)
        decision = decide(validate(result["answers"]), STATE)
    except urllib.error.HTTPError as error:
        print(json.dumps({"route": "review", "executed": False, "http_status": error.code}))
        raise SystemExit(1)
    except (ValueError, KeyError, TypeError, urllib.error.URLError, TimeoutError):
        print(json.dumps({"route": "review", "executed": False, "reason": "evaluation_failed"}))
        raise SystemExit(1)
    print(json.dumps({"mode": "live" if args.live else "illustrative_fixture",
        "model": result.get("model"), "decision": decision,
        "answers": result["answers"]}, indent=2))

if __name__ == "__main__":
    main()
