"""Answer a customer from your own records: look the recall up, then answer.

The complaints are real: filed with the US road-safety regulator (NHTSA) in 2026, each naming a recall campaign. The
records the tool reads are real too: NHTSA's recall records for the same vehicles, as its public service returned
them on 2 December 2026. Run it with `pip install openai`, then `python tools-recall-lookup.py`. The API is free and
needs no key.
"""
# === setup ===
import contextlib
import io
import json
import re
import textwrap
from pathlib import Path

from openai import OpenAI

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

# === the loop ===
class Final(Exception):
    """A function raises this when there is nothing more to try. Its message goes to the model as the result,
    and no tools are offered after it, so the model answers in words."""


def run_tools(messages, tools, functions, tool_choice="auto", max_turns=6):
    """Run the conversation until the model answers in words. functions: {tool name: Python function}."""
    messages = list(messages)
    for _ in range(max_turns):
        offer = {"tools": tools, "tool_choice": tool_choice} if tools else {"temperature": 0}
        reply = client.chat.completions.create(model="nenya", messages=messages, **offer)
        message = reply.choices[0].message
        if not message.tool_calls:
            return message.content
        messages.append(message.model_dump(exclude_none=True))     # the model's message, as it came
        for call in message.tool_calls:
            arguments = json.loads(call.function.arguments)        # a JSON string: parse it, then check it
            print(f"-> {call.function.name}({arguments})")
            try:
                result = json.dumps(functions[call.function.name](**arguments))
            except Final as final:          # nothing more to try: a sentence for the model, and no more tools
                result, tools = str(final), None
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
        tool_choice = "auto"                # a forced first step must not force every later one
    raise RuntimeError("the model kept calling tools: stop and look")


def tool(name, description, properties, required):
    return {"type": "function", "function": {"name": name, "description": description, "parameters": {
        "type": "object", "properties": properties, "required": required}}}

# === the records ===
DATA = json.loads((Path(__file__).parent / "data" / "tools-recall-lookup.json").read_text())
RECALLS = DATA["recalls"]                   # NHTSA's recall records, by "year make model"


def campaign_numbers(text):
    """The NHTSA campaign numbers in a text: two digits, V or E, six digits."""
    return sorted(set(re.findall(r"\b\d{2}[VE]\d{6}\b", str(text).upper())))


def recalls_for(make, model, model_year):
    """The records of a vehicle. People write "Promaster 3500" where the records say "Promaster", so words are
    dropped from the end of the model's name until something matches."""
    words = str(model).split()
    while words:
        records = RECALLS.get(f"{model_year} {make} {' '.join(words)}".lower())
        if records:
            return records
        words = words[:-1]
    return []

# === the tool ===
SYSTEM = """You are the assistant of a vehicle recall desk. You answer from NHTSA's recall records.

Rules:
- Always look the recall up first.
- Answer from what the tool returns: say whether the recall is on record for the vehicle, and what the remedy is.
- Keep answers short and plain."""

VEHICLE = {"make": {"type": "string", "description": "The vehicle's make (brand)"},
           "model": {"type": "string", "description": "The vehicle's model, without the make"},
           "model_year": {"type": "integer", "description": "The model year"}}
TOOLS = [tool("find_recalls", "Look recall campaigns up in NHTSA's records for a vehicle.",
              dict(VEHICLE, campaigns={"type": "array", "items": {"type": "string"},
                                       "description": "Every NHTSA campaign number the customer mentions, "
                                                      "such as 24V123000"}),
              ["make", "model", "model_year", "campaigns"])]
looked_up = []                              # every call the model makes, to check afterwards


def find_recalls(make, model, model_year, campaigns):
    """Your own code: an exact look-up. Here it reads a file. In production it asks your database, or NHTSA's
    service. It returns the records asked for and nothing else."""
    wanted = campaign_numbers(campaigns)    # keep what has the shape of a campaign number, whatever else came
    looked_up.append({"make": make, "model": model, "model_year": model_year, "campaigns": wanted})
    found = [{"campaign": r["NHTSACampaignNumber"], "component": r["Component"].split(":")[0].capitalize(),
              "remedy": r["Remedy"]}
             for r in recalls_for(make, model, model_year) if r["NHTSACampaignNumber"] in wanted]
    if not found:                           # nothing to report: a sentence for the model, and no more tools
        raise Final(f"NHTSA has no recall {' or '.join(wanted) or 'with that number'} on record for a {model_year} "
                    f"{make} {model}. Tell the user so, and ask them to check the campaign number and the vehicle.")
    return {"on_record": found,
            "not_on_record_for_this_vehicle": [c for c in wanted if c not in [f["campaign"] for f in found]]}


QUESTION = "Is the recall they mention on NHTSA's record for their vehicle's model and year, and what is the remedy?"


def ask(complaint):
    """The model's answer to one customer's complaint, with the look-up done on the way."""
    return run_tools([{"role": "system", "content": SYSTEM},
                      {"role": "user", "content": f"A customer writes:\n\n{complaint}\n\n{QUESTION}"}],
                     TOOLS, {"find_recalls": find_recalls})

# === the request ===
customer = DATA["examples"][0]
print(textwrap.fill(customer["document"], 100))
print()
answer = ask(customer["document"])
print(textwrap.fill(answer, 100))

# === check it ===
call, vehicle = looked_up[-1], customer["vehicle"]      # the vehicle on the complaint's form: the test set's answer
record = [r for r in recalls_for(**vehicle) if r["NHTSACampaignNumber"] in campaign_numbers(customer["document"])][0]
print(f"looked up:            {call['model_year']} {call['make']} {call['model']}, {call['campaigns']}")
print(f"the complaint's form: {vehicle['model_year']} {vehicle['make']} {vehicle['model']}")
print(f"the customer names:   {campaign_numbers(customer['document'])}")
print()
print("NHTSA's record of the remedy:")
print(textwrap.fill(record["Remedy"], 100))

# === three customers ===
for customer in DATA["examples"]:
    print(textwrap.fill(ask(customer["document"]), 100))
    print()

# === a recall that is not on record ===
customer = DATA["not_on_record"]
print(textwrap.fill(customer["document"], 100))
print()
print(textwrap.fill(ask(customer["document"]), 100))

# === the first version ===
LIST_TOOLS = [tool("list_recalls", "List the safety recalls NHTSA has on record for a vehicle.", VEHICLE,
                   ["make", "model", "model_year"])]


def list_recalls(make, model, model_year):
    """The first version of the tool: every recall of the vehicle, for the model to find the right one in."""
    records = recalls_for(make, model, model_year)
    if not records:
        raise Final(f"NHTSA has no recall on record for a {model_year} {make} {model}. Tell the user so, and ask "
                    "them to check the make, the model and the year.")
    return [{"campaign": r["NHTSACampaignNumber"], "component": r["Component"].split(":")[0].capitalize(),
             "remedy": r["Remedy"]} for r in records]


def ask_with_list(complaint):
    return run_tools([{"role": "system", "content": SYSTEM},
                      {"role": "user", "content": f"A customer writes:\n\n{complaint}\n\n{QUESTION}"}],
                     LIST_TOOLS, {"list_recalls": list_recalls})

# === does the answer say what the records say ===
def says_none(answer):
    """Does an answer say that the recall is not on record? A rule of thumb for English, good enough to count with."""
    return bool(re.search(r"(?i)^no\b|\bno (?:such |matching )?recalls?\b(?! repair| remedy| part)|"
                          r"\bnot (?:on|in|listed|found|appear|show|match|have)|did not turn up|no record", answer))


def agrees(answer, customer):
    """Does an answer say what the records say? A recall that is on record must not be denied, one that is not
    must not be confirmed, and no campaign number may come from nowhere."""
    if answer is None:
        return False
    on_record = {r["NHTSACampaignNumber"] for r in recalls_for(**customer["vehicle"])}
    named = set(campaign_numbers(customer["document"]))
    found = named & on_record
    if set(campaign_numbers(answer)) - on_record - named:
        return False                        # a number that is in no record and that the customer did not write
    if not found:
        return says_none(answer)
    if found != named:                      # some are on record and some are not: it has to name the ones that are
        return found <= set(campaign_numbers(answer))
    return not says_none(answer)


def attempt(function, complaint):
    """An answer, without the lines run_tools prints. A conversation that fails counts as no answer."""
    with contextlib.redirect_stdout(io.StringIO()):
        try:
            return function(complaint)
        except (RuntimeError, TypeError, ValueError):
            return None

# === measure it ===
customers = DATA["sample"]                  # every complaint of the test set that names a recall and its vehicle
exact = said = 0
for customer in customers:
    start = len(looked_up)
    answer = attempt(ask, customer["document"])
    calls, form = looked_up[start:], customer["vehicle"]
    exact += (len(calls) == 1 and str(calls[0]["make"]).lower() == form["make"].lower()
              and calls[0]["model_year"] == form["model_year"]
              and recalls_for(calls[0]["make"], calls[0]["model"], calls[0]["model_year"]) == recalls_for(**form)
              and calls[0]["campaigns"] == campaign_numbers(customer["document"]))
    said += agrees(answer, customer)
listed = sum(agrees(attempt(ask_with_list, customer["document"]), customer) for customer in customers)

print(f"one look-up, for the form's vehicle and the customer's campaign numbers:  {exact} of {len(customers)}")
print(f"the answer says what the records say:                                    {said} of {len(customers)}")
print(f"the same with the first version, which returns the vehicle's whole list: {listed} of {len(customers)}")
