"""Extract from a PDF or a scan.

The API takes text. A PDF is turned into text on your own machine with Docling (MIT licence, runs locally), and then
the extraction recipe runs on that text unchanged. The PDF is real: the report of a 2026 aviation accident as the US
National Transportation Safety Board publishes it, and the same report as a scan.

    pip install openai docling
    python extract-pdfs-and-scans.py

The first run downloads Docling's models (layout, tables, OCR). The API is free and needs no key.
"""
# === setup ===
import json
import time
from pathlib import Path

from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import OcrMode, PdfPipelineOptions
from docling.document_converter import DocumentConverter, PdfFormatOption
from openai import OpenAI

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

# === 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)

# === convert the PDF ===
def pdf_to_text(path, scanned=False):
    """The text of a PDF as Markdown, tables included. It runs on this machine: nothing is sent anywhere.
    scanned=True reads every page with OCR, for a file that is only pictures of pages."""
    options = PdfPipelineOptions(do_ocr=scanned)            # a PDF that has a text layer needs no OCR
    if scanned:
        options.ocr_options.mode = OcrMode.FULL_PAGE        # read the whole page, not only the pictures in it
    converter = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=options)})
    return converter.convert(path).document.export_to_markdown()

# === a PDF with a text layer ===
start = time.perf_counter()
text = pdf_to_text(HERE / "files" / "NTSB-ERA26LA216.pdf")
print(f"[converted in {time.perf_counter() - start:.0f} s: {len(text):,} characters]")
print()
print(text)

# === the request ===
DATA = json.loads((HERE / "data" / "extract-pdfs-and-scans.json").read_text())
KIND = DATA["kind"]                         # "aviation accident report"
FIELDS = DATA["fields"]                     # the seven fields of the accident-report cookbook, as they are there

record = extract(KIND, text, FIELDS)
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)


report = DATA["documents"][0]               # the test set's answer for this report
for name, value in record.items():
    verdict = "right" if same(value, report["answer"][name]) else f"the narrative has {report['answer'][name]!r}"
    print(f"{name:<15} {value!r:<14} {verdict}")

# === what only the tables say ===
TABLE_FIELDS = DATA["table_fields"]
for field in TABLE_FIELDS:
    print(f"- {field['name']} ({field['type']}): {field['description']}")

from_tables = extract(KIND, text, TABLE_FIELDS)
print()
for name, value in from_tables.items():
    verdict = "right" if same(value, report["table_answer"][name]) else f"WRONG, the PDF has {report['table_answer'][name]!r}"
    print(f"{name:<17} {value!r:<14} {verdict}")

# === a scan ===
start = time.perf_counter()
scan_text = pdf_to_text(HERE / "files" / "NTSB-ERA26LA216-scan.pdf", scanned=True)
print(f"[converted in {time.perf_counter() - start:.0f} s: {len(scan_text):,} characters]")
print()
print(scan_text[scan_text.index("## Meteorological"):scan_text.index("## Wreckage")])

from_scan = extract(KIND, scan_text, FIELDS + TABLE_FIELDS)
from_pdf = {**record, **from_tables}
print("the same twelve values from the scan as from the PDF:", from_scan == from_pdf)
