"""TypeSafe AI の実 API 用コード例。

実行には `pip install -r ../requirements.txt` と
`TYPESAFE_API_KEY` が必要。教材のオフライン確認では実行しない。
"""

from typesafe_sdk import Choice, Noul, Score, TypeSafeAPIError, TypeSafeClient


def choose_action(result) -> str:
    """回答を組み合わせる純粋な分岐。外部への副作用は持たない。"""
    refund = result.nouls["is_refund"].noul >= 0.8
    route = result.choices["route"]
    urgent = result.scores["urgency"].score >= 1.5
    enough_confidence = route.confidence >= 0.8 and result.scores["urgency"].confidence >= 0.6
    if refund and route.choice == "billing" and urgent and enough_confidence:
        return "billing:urgent-refund-review"
    if route.confidence < 0.5 or result.scores["urgency"].confidence < 0.5:
        return "human-review:uncertain"
    return f"queue:{route.choice}"


def classify_ticket(ticket: str) -> None:
    questions = {
        "is_refund": Noul(instructions="Does `ticket` request a refund?"),
        "route": Choice(
            instructions="Which team should handle `ticket`?",
            criteria={
                "billing": "Payment, charge, or refund issues.",
                "technical": "A software bug or integration failure.",
                "other": "Anything outside billing and technical support.",
            },
        ),
        "urgency": Score(
            instructions="How urgent is `ticket`?",
            criteria=[
                "Can wait; no meaningful near-term impact.",
                "Should be handled this week; workaround or limited impact exists.",
                "Needs attention today; time-sensitive or blocking impact.",
            ],
        ),
    }
    try:
        with TypeSafeClient() as client:
            result = client.system_one(state={"ticket": ticket}, questions=questions)
    except TypeSafeAPIError as error:
        # status/request_id は運用ログに使える。API キーや本文を出力しない。
        print(f"TypeSafe API failed: status={error.status}, request_id={error.request_id}")
        raise

    print("refund probability:", result.nouls["is_refund"].noul)
    print("route:", result.choices["route"].choice)
    print("urgency score:", result.scores["urgency"].score)
    print("urgency confidence:", result.scores["urgency"].confidence)
    print("suggested action:", choose_action(result))


if __name__ == "__main__":
    classify_ticket("二重請求です。今日中に返金してください。")
