"""Run the patched XBRL backend (typed-dimension guard) on the Apple instance."""

import importlib.util
import json
import time
from collections import Counter
from pathlib import Path

from docling.datamodel.backend_options import XBRLBackendOptions
from docling.datamodel.base_models import InputFormat
from docling.datamodel.document import InputDocument

here = Path(__file__).parent
spec = importlib.util.spec_from_file_location("patched_xbrl_backend", here / "patched_xbrl_backend.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)

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=mod.XBRLDocumentBackend,
    backend_options=options,
    filename=src.name,
)
backend = mod.XBRLDocumentBackend(in_doc=in_doc, path_or_stream=src, options=options)
doc = backend.convert()
elapsed = time.time() - start

kv = doc.key_value_items
cells = [c for item in kv for c in item.graph.cells]
links = [ln for item in kv for ln in item.graph.links]
label_counts = Counter(str(c.label) for c in cells)
md = doc.export_to_markdown()

report = {
    "elapsed_s": round(elapsed, 1),
    "texts": len(doc.texts),
    "tables": len(doc.tables),
    "key_value_items": len(kv),
    "graph_cells": len(cells),
    "graph_links": len(links),
    "cell_label_counts": dict(label_counts),
    "title": doc.texts[0].text if doc.texts else None,
    "markdown_chars": len(md),
    "contains_109417": "109,417" in md or "109417" in md,
    "prov_populated": sum(1 for c in cells if c.prov),
    "item_ref_populated": sum(1 for c in cells if c.item_ref),
}
(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 = [c for c in cells if "109,417" in c.text or "109417" in c.text]
for c in sample[:4]:
    print("MATCH:", c.label, repr(c.text), "orig=", repr(str(c.orig))[:80])
for c in cells[:10]:
    print(c.label, repr(c.text[:70]), "orig=", repr(str(c.orig))[:60])
