"""Pull the vehicle and the mileage out of a consumer complaint.

The complaints are real: filed with the US road-safety regulator (NHTSA) in 2026, each with the values of the form
the filer filled in beside the text. Run it with `pip install openai`, then `python extract-complaint-details.py`.
The API is free and needs no key.
"""
# === setup ===
import json
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 extract(kind, document, fields, max_tokens=800):
    """{field: value or None}. fields: [{"name", "type", "description"}], plus "schema" for lists and objects."""
    lines = "\n".join(f"- {f['name']} ({f['type']}): {f['description']}" for f in fields)
    system = (f"You extract structured data from {kind}s. For each document the user sends, give these fields.\n\n"
              f"Fields:\n{lines}\n\n"
              "Answer with one JSON object with exactly these keys. Use null for a field the text does not give.")
    properties = {f["name"]: f.get("schema") or {"type": [f["type"], "null"]} for f in fields}
    schema = {"type": "object", "properties": properties, "required": [f["name"] for f in fields],
              "additionalProperties": False}
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "system", "content": system}, {"role": "user", "content": document}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=max_tokens,
        response_format={"type": "json_schema", "json_schema": {"name": "record", "schema": schema}},
    )
    choice = reply.choices[0]
    if choice.finish_reason != "stop":      # "length": the JSON was cut off and will not parse
        raise RuntimeError(f"the reply was cut off ({choice.finish_reason}): raise max_tokens")
    return json.loads(choice.message.content)

# === the data ===
DATA = json.loads((Path(__file__).parent / "data" / "extract-complaint-details.json").read_text())
KIND = DATA["kind"]                         # "vehicle safety complaint"
FIELDS = DATA["fields"]

for field in FIELDS:
    print(f"- {field['name']} ({field['type']}): {field['description']}")

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

record = extract(KIND, complaint["document"], FIELDS)
print()
print(json.dumps(record, indent=2))

# === check it ===
def same(value, answer):
    """Is an extracted value the right one? Text is compared by its letters and digits (case, spaces and
    punctuation aside), numbers as numbers, and a field the document does not state has to be null."""
    if value is None or answer is None:
        return value is None and answer is None
    if isinstance(answer, (int, float)):
        return isinstance(value, (int, float)) and value == answer
    squeeze = lambda s: "".join(c for c in str(s).casefold() if c.isalnum())      # noqa: E731
    return squeeze(value) == squeeze(answer)


for name, value in record.items():
    verdict = "right" if same(value, complaint["answer"][name]) else f"WRONG, the form has {complaint['answer'][name]!r}"
    print(f"{name:<16} {value!r:<15} {verdict}")

# === three complaints ===
for complaint in DATA["examples"]:
    record = extract(KIND, complaint["document"], FIELDS)
    print(json.dumps(record))

# === is every value in the text? ===
def not_in_text(record, text):
    """The fields whose value cannot be found in the text. A number is looked for with and without the comma."""
    missing = []
    for name, value in record.items():
        if value is None:
            continue
        spellings = {str(value), f"{value:,}"} if isinstance(value, int) else {str(value)}
        if not any(spelling.lower() in text.lower() for spelling in spellings):
            missing.append(name)
    return missing


sample = DATA["sample"]                     # every complaint the test set has an answer for on all five fields
records = [extract(KIND, complaint["document"], FIELDS) for complaint in sample]
flagged = [(complaint, record) for complaint, record in zip(sample, records)
           if not_in_text(record, complaint["document"])]
print(f"{len(sample) - len(flagged)} of {len(sample)} records have every value in the text")
for complaint, record in flagged:
    print(f"   {complaint['id']}: {not_in_text(record, complaint['document'])} is not in the text as written")

# === measure it ===
right = {field["name"]: 0 for field in FIELDS}
complete = 0
for complaint, record in zip(sample, records):
    ok = {name: same(record[name], complaint["answer"][name]) for name in right}
    complete += all(ok.values())
    for name in right:
        right[name] += ok[name]

print(f"{complete} of {len(sample)} complaints with every field right")
for name, n in right.items():
    print(f"{name:<16} {n} of {len(sample)}")
