#!/usr/bin/env python3
"""T16: the same PDFs through MarkItDown, Docling and pymupdf4llm (default settings, CPU only, one process per tool).
usage: t16_compare.py <tool: markitdown|docling|pymupdf4llm> -> evidence/T16/<tool>.json and outputs/<tool>__<file>.md"""
import json, re, resource, sys, time, platform, importlib.metadata as m
from pathlib import Path
tool = sys.argv[1]; S = Path("lab/corpus/synthetic"); R = Path("lab/corpus/real"); O = Path("evidence/T16/outputs")
FILES = [S / f for f in ["pdf-text.pdf", "pdf-table-bordered.pdf", "pdf-table-borderless.pdf", "pdf-table-merged-cells.pdf", "pdf-wide-12-column-table.pdf", "pdf-two-column.pdf", "pdf-header-footer.pdf", "pdf-bullets-numbered.pdf", "pdf-cjk.pdf", "pdf-scanned-300dpi.pdf"]] + [R / "real-pdf-cfr-21-sec-1-1.pdf", R / "real-pdf-budget-fy2024.pdf"]
t0 = time.time()
if tool == "markitdown":
    from markitdown import MarkItDown; md = MarkItDown(); conv = lambda p: md.convert(str(p)).markdown; ver = m.version("markitdown")
elif tool == "docling":
    from docling.document_converter import DocumentConverter; dc = DocumentConverter(); conv = lambda p: dc.convert(str(p)).document.export_to_markdown(); ver = m.version("docling")
elif tool == "pymupdf4llm":
    import pymupdf4llm; conv = lambda p: pymupdf4llm.to_markdown(str(p)); ver = m.version("pymupdf4llm")
setup = round(time.time() - t0, 1); rows = []
def pages(p):
    import pymupdf; return len(pymupdf.open(str(p)))
for p in FILES:
    t = time.time(); err = ""; txt = ""
    try: txt = conv(p)
    except Exception as e: err = f"{type(e).__name__}: {str(e)[:100]}"
    sec = round(time.time() - t, 2); (O / f"{tool}__{p.name}.md").write_text(txt or err, encoding="utf-8")
    heads = len(re.findall(r"(?m)^#{1,6} ", txt)); pipe = len(re.findall(r"(?m)^\|.*\|\s*$", txt)); sep = len(re.findall(r"(?m)^\|\s*:?-{2,}", txt))
    rows.append({"file": p.name, "pages": pages(p), "seconds": sec, "characters": len(txt), "headings": heads, "table_rows": max(0, pipe - sep), "tables": sep, "peak_rss_mb_so_far": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024), "error": err}); print(rows[-1], flush=True)
json.dump({"tool": tool, "version": ver, "python": platform.python_version(), "machine": platform.platform(), "cpus": __import__("os").cpu_count(), "import_and_setup_seconds": setup, "date": time.strftime("%Y-%m-%d"), "rows": rows}, open(f"evidence/T16/{tool}.json", "w"), indent=1)
