"""Route a vehicle safety complaint to the right engineering team.

The complaints are real: filed with the US road-safety regulator (NHTSA) in 2026, each with the component its filer
ticked on the form. Run it with `pip install openai`, then `python classify-safety-complaints.py`. The API is free
and needs no key.
"""
# === setup ===
import json
import math
import textwrap
from pathlib import Path

from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")

# === the recipe ===
def classify(question, text, labels, heading="Text", descriptions=None, allow_none=False):
    """(label, confidence)"""
    options = "\n".join(f"- {label}: {descriptions[label]}" if descriptions else f"- {label}" for label in labels)
    prompt = f"{question}\n\n{heading}:\n{text}\n\nOptions:\n{options}\n\nAnswer with the label only."
    if allow_none:
        prompt += ' If none of the options fits, answer "none".'
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "user", "content": prompt}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=24,
        logprobs=True,                      # for the confidence
        extra_body={"structured_outputs": {"choice": labels + (["none"] if allow_none else [])}},
    )
    choice = reply.choices[0]
    tokens = [t for t in choice.logprobs.content if not t.token.startswith("<|")]
    confidence = math.exp(sum(t.logprob for t in tokens))
    return choice.message.content, confidence

# === the data ===
DATA = json.loads((Path(__file__).parent / "data" / "classify-safety-complaints.json").read_text())
QUESTION = DATA["question"]
COMPONENTS = DATA["labels"]                 # the twelve components a complaint can be about
ABOUT = DATA["descriptions"]                # a few words on what each one covers

print(QUESTION)
for name in COMPONENTS:
    print(f"- {name}: {ABOUT[name]}")

# === the request ===
complaint = DATA["examples"][0]
print(textwrap.fill(complaint["text"], 100))

label, confidence = classify(QUESTION, complaint["text"], COMPONENTS, heading="Complaint", descriptions=ABOUT)
print()
print(f"model: {label} ({confidence:.0%} sure)")
print(f"filer: {complaint['label']}")

# === six complaints ===
for complaint in DATA["examples"]:
    label, confidence = classify(QUESTION, complaint["text"], COMPONENTS, heading="Complaint", descriptions=ABOUT)
    vehicle = f"{complaint['model_year']} {complaint['make']} {complaint['model']}"
    print(f"{label:<24} {confidence:4.0%}   {vehicle:<28} {complaint['text'][:44]}...")

# === the unsure ones go to a person ===
THRESHOLD = 0.9
for complaint in DATA["review"] + DATA["examples"][:2]:
    label, confidence = classify(QUESTION, complaint["text"], COMPONENTS, heading="Complaint", descriptions=ABOUT)
    action = f"route to {label}" if confidence >= THRESHOLD else f"a person looks (the model leans to {label})"
    print(f"{confidence:4.0%}   {action:<52} filer: {complaint['label']}")

# === measure it ===
sample = DATA["sample"]                     # 60 complaints, taken without looking at the answers
agree = sure = sure_agree = 0
for complaint in sample:
    label, confidence = classify(QUESTION, complaint["text"], COMPONENTS, heading="Complaint", descriptions=ABOUT)
    agree += label == complaint["label"]
    if confidence >= THRESHOLD:
        sure += 1
        sure_agree += label == complaint["label"]

print(f"{agree} of {len(sample)} agree with the filer ({agree / len(sample):.0%})")
print(f"the model is at least {THRESHOLD:.0%} sure of {sure}; {sure_agree} of those agree ({sure_agree / sure:.0%})")
print(f"so {len(sample) - sure} of {len(sample)} would go to a person")
