"""Run docling's XBRLDocumentBackend on the Apple 10-Q instance document."""

import json
import time
from pathlib import Path

from docling.backend.xml.xbrl_backend import XBRLBackendOptions, XBRLDocumentBackend
from docling.datamodel.base_models import InputFormat
from docling.datamodel.document import InputDocument

here = Path(__file__).parent
src = here / "instancedir" / "aapl-20260627_htm.xml"

options = XBRLBackendOptions(enable_remote_fetch=True, enable_local_fetch=True, taxonomy=here / "instancedir")
start = time.time()
in_doc = InputDocument(
    path_or_stream=src,
    format=InputFormat.XML_XBRL,
    backend=XBRLDocumentBackend,
    backend_options=options,
    filename=src.name,
)
backend = XBRLDocumentBackend(in_doc=in_doc, path_or_stream=src, options=options)
doc = backend.convert()
elapsed = time.time() - start

kv = doc.key_value_items
cells = sum(len(item.graph.cells) for item in kv)
links = sum(len(item.graph.links) for item in kv)
report = {
    "elapsed_s": round(elapsed, 1),
    "texts": len(doc.texts),
    "tables": len(doc.tables),
    "key_value_items": len(kv),
    "graph_cells": cells,
    "graph_links": links,
    "title": doc.texts[0].text if doc.texts else None,
}
md = doc.export_to_markdown()
report["markdown_chars"] = len(md)
report["contains_109417"] = "109,417" in md or "109417" in md

(here / "xbrl_backend_report.json").write_text(json.dumps(report, indent=2))
(here / "aapl-instance.docling.md").write_text(md)
(here / "aapl-instance.docling.json").write_text(doc.model_dump_json())
print(json.dumps(report, indent=2))

# Sample of the key-value graph: first 12 cells.
if kv:
    for cell in kv[0].graph.cells[:12]:
        print(f"{cell.label}: {cell.text[:80]!r} orig={str(cell.orig)[:60]!r}")
