#!/usr/bin/env python3
"""T16 (Pandoc): the same files through MarkItDown 0.1.9 and Pandoc (-t gfm, default settings). usage: t16_pandoc.py <pandoc binary> -> evidence/T16/pandoc.json, outputs/pandoc-*"""
import json, re, subprocess, sys, time
from pathlib import Path
from markitdown import MarkItDown
PANDOC = sys.argv[1]; S = Path("lab/corpus/synthetic"); P = Path("public/samples"); O = Path("evidence/T16/outputs")
FILES = [P / "report.docx", P / "docx-table-header.docx", P / "docx-merged-cells.docx", P / "deck.pptx", P / "workbook.xlsx", S / "report.rtf", S / "report.odt", S / "deck.odp", S / "workbook.ods", P / "book.epub", P / "page.html", P / "data.csv", S / "csv-tab.tsv", P / "notebook.ipynb", P / "pdf-text.pdf", P / "pptx-basic.ppt", P / "report.doc"]
md = MarkItDown(); rows = []
def stats(t): return {"characters": len(t), "headings": len(re.findall(r"(?m)^#{1,6} ", t)), "table_rows": len(re.findall(r"(?m)^\|", t))}
for f in FILES:
    r = {"file": f.name}
    t = time.time(); err = ""; txt = ""
    try: txt = md.convert(str(f)).markdown
    except Exception as e: err = type(e).__name__
    r["markitdown_seconds"] = round(time.time() - t, 2); r["markitdown_error"] = err; r.update({"markitdown_" + k: v for k, v in stats(txt).items()}); (O / f"markitdown-all__{f.name}.md").write_text(txt or err, encoding="utf-8")
    t = time.time(); p = subprocess.run([PANDOC, str(f), "-t", "gfm", "--wrap=none"], capture_output=True, text=True); r["pandoc_seconds"] = round(time.time() - t, 2)
    r["pandoc_error"] = (p.stderr.strip().splitlines() or [""])[0][:100] if p.returncode else ""; r.update({"pandoc_" + k: v for k, v in stats(p.stdout).items()}); (O / f"pandoc__{f.name}.md").write_text(p.stdout or r["pandoc_error"], encoding="utf-8")
    rows.append(r); print(r, flush=True)
json.dump(rows, open("evidence/T16/pandoc.json", "w"), indent=1)
import csv
with open("src/data/comparison-pandoc.csv", "w", newline="") as fo: w = csv.DictWriter(fo, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
