"""Replay eight synthetic Jev answers. --live explicitly makes one paid API call.

This prints proposed queues only. It never contacts a help desk or executes a route.
The numerical thresholds are illustrative, chosen after the saved model response.
"""
import argparse
import json
import math
import os
from pathlib import Path
import urllib.request

HERE = Path(__file__).resolve().parent
QUEUES = {"billing", "account_access", "product_help"}


def proposed_queue(route, human, *, route_floor, human_no_ceiling,
                   mandatory_review=False):
    """Apply application policy to typed answers; return a proposal, not an action."""
    def review(reason):
        return {"queue": "human_review", "reason": reason}

    if mandatory_review:
        return review("application_policy")
    if not isinstance(route, dict) or not isinstance(human, dict):
        return review("missing_answer")
    if route.get("type") != "choice" or human.get("type") != "noul":
        return review("unexpected_answer_type")
    confidence = route.get("confidence")
    p_human = human.get("noul")
    for value in (confidence, p_human):
        if (isinstance(value, bool) or not isinstance(value, (int, float))
                or not math.isfinite(value) or not 0 <= value <= 1):
            return review("invalid_probability")
    if p_human > human_no_ceiling:
        return review("human_requested_or_uncertain")
    choice = route.get("choice")
    if choice == "no_match":
        return review("no_single_supported_team")
    if choice not in QUEUES:
        return review("unknown_team")
    if confidence < route_floor:
        return review("route_uncertain")
    return {"queue": choice, "reason": "eligible_queue_proposal"}


def request_once(payload):
    # Run on a server. Never put the API key in a webpage or a saved request file.
    key = os.environ.get("TYPESAFE_API_KEY")
    if not key:
        raise RuntimeError("Set TYPESAFE_API_KEY in the server environment")
    request = urllib.request.Request(
        "https://api.typesafe.ai/v1/systemone",
        data=json.dumps(payload).encode(),
        headers={"Authorization": "Bearer " + key,
                 "Content-Type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=20) as response:
        return json.load(response)


def summarize(response, cases, floor):
    rows = []
    answers = response.get("answers", {})
    for case in cases:
        route = answers.get(case["id"] + "_route")
        human = answers.get(case["id"] + "_human")
        decision = proposed_queue(
            route, human, route_floor=floor, human_no_ceiling=0.10
        )
        rows.append({
            "id": case["id"], "message": case["message"],
            "expected_route": case["expected_route"],
            "model_route": route.get("choice") if route else None,
            "confidence": route.get("confidence") if route else None,
            "human_yes_probability": human.get("noul") if human else None,
            **decision,
        })
    proposals = [r for r in rows if r["queue"] != "human_review"]
    return {
        "route_floor": floor,
        "human_no_ceiling": 0.10,
        "queue_proposals": len(proposals),
        "human_review": len(rows) - len(proposals),
        "proposal_disagreements": sum(
            r["queue"] != r["expected_route"] for r in proposals
        ),
        "rows": rows,
    }


def self_test():
    confident = {"type": "choice", "choice": "billing", "confidence": 1.0}
    no_human = {"type": "noul", "noul": 0.01}
    settings = {"route_floor": 0.90, "human_no_ceiling": 0.10}
    assert proposed_queue(None, no_human, **settings)["queue"] == "human_review"
    assert proposed_queue(confident, no_human, mandatory_review=True,
                          **settings)["queue"] == "human_review"
    assert proposed_queue(confident, {"type": "noul", "noul": 0.99},
                          **settings)["queue"] == "human_review"
    assert proposed_queue({**confident, "choice": "no_match"}, no_human,
                          **settings)["queue"] == "human_review"
    assert proposed_queue({**confident, "confidence": float("nan")}, no_human,
                          **settings)["queue"] == "human_review"
    assert proposed_queue({**confident, "choice": "delete_account"}, no_human,
                          **settings)["queue"] == "human_review"
    assert proposed_queue(confident, no_human, **settings)["queue"] == "billing"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--live", action="store_true")
    args = parser.parse_args()
    self_test()
    payload = json.loads((HERE / "typesafe-routing-request.json").read_text())
    cases = json.loads((HERE / "typesafe-routing-expected.json").read_text())["cases"]
    if args.live:
        try:
            response = request_once(payload)
        except Exception as exc:
            # An application should retain the incoming item for human triage.
            # This demo prints a failure status and does not retry or take action.
            print(json.dumps({"status": "human_review", "reason": "service_failure",
                              "error_type": type(exc).__name__}))
            return
    else:
        response = json.loads((HERE / "typesafe-routing-response.json").read_text())
    report = {
        "mode": "live" if args.live else "saved_response_replay",
        "synthetic": True,
        "model": response.get("model"), "usage": response.get("usage"),
        "warning": "Thresholds are post-hoc illustrations, not validated settings.",
        "policies": [summarize(response, cases, floor) for floor in (0.80, 0.90)],
    }
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()
