"""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 = {'claim': 'Customers can cancel their subscription at any time.', 'quoted_passage': 'You may cancel your subscription at any time from Billing.', 'surrounding_context': 'Cancellation stops future renewal; refund rules are separate.', 'source_metadata': {'id': 'policy-1', 'title': 'Subscription policy', 'retrieved_at': '2026-09-20'}}
QUESTIONS = {'verdict': {'type': 'choice', 'instructions': 'Does the quoted passage support the claim in its surrounding context?', 'criteria': {'supports': 'The passage supports the claim as stated', 'contradicts': 'The passage conflicts with the claim', 'insufficient': 'The source does not establish the claim'}}}
FIXTURE = {'verdict': {'type': 'choice', 'choice': 'supports', 'confidence': 0.92, 'probabilities': {'supports': 0.9466666666666668, 'contradicts': 0.026666666666666616, 'insufficient': 0.026666666666666616}}}

def decide(answers, state):
    verdict = answers["verdict"]
    if verdict["confidence"] < .9:
        route = "review"
    elif verdict["choice"] == "supports":
        route = "accept_evidence_match"
    elif verdict["choice"] == "contradicts":
        route = "reject"
    else:
        route = "seek_more_evidence"
    return {"route": route, "source_id": state["source_metadata"]["id"],
            "source_authenticity_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()
