"""Turn an accident report into a database row.

The reports are real: preliminary reports of 2026 aviation accidents, published by the US National Transportation
Safety Board, each with the values of the NTSB's own record of the case. Run it with `pip install openai`, then
`python extract-accident-reports.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-accident-reports.json").read_text())
KIND = DATA["kind"]                         # "aviation accident report"
FIELDS = DATA["fields"]                     # what to pull out: a name, a type and a description for each field

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

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

record = extract(KIND, report["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, report["answer"][name]) else f"WRONG, the NTSB has {report['answer'][name]!r}"
    print(f"{name:<15} {value!r:<14} {verdict}")

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

# === one field for each fact ===
without_make = [field for field in FIELDS if field["name"] != "aircraft_make"]
for report, record in zip(DATA["examples"], records):
    alone = extract(KIND, report["document"], without_make)
    print(f"asked with aircraft_make: {record['aircraft_model']!r:<12} asked without it: {alone['aircraft_model']!r}")

# === measure it ===
sample = DATA["sample"]                     # every report the test set has an answer for on all seven fields
right = {field["name"]: 0 for field in FIELDS}
complete = 0
for report in sample:
    record = extract(KIND, report["document"], FIELDS)
    ok = {name: same(record[name], report["answer"][name]) for name in right}
    complete += all(ok.values())
    for name in right:
        right[name] += ok[name]

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