"""Audit a DOCX converted from a PDF: what survived, what turned into plain text.

Usage: python pdf_to_word_audit.py converted.docx [source.pdf]
Needs: pip install python-docx  (and pymupdf when a source PDF is given)
Reports facts only; open the DOCX in Word to judge layout.
"""
import re, sys, zipfile
import docx
from docx.oxml.ns import qn

def audit(docx_path, pdf_path=None):
    d = docx.Document(docx_path)
    body = d.element.body
    paras = [p for p in d.paragraphs if p.text.strip()]
    xml_words = len(" ".join(t.text for t in body.iter(qn("w:t"))).split())
    print(f"paragraphs with text (outside tables): {len(paras)}")
    print(f"words in document body: {xml_words}")
    if pdf_path:
        import pymupdf
        with pymupdf.open(pdf_path) as pdf:
            pdf_words = sum(len(pg.get_text("words")) for pg in pdf)
        print(f"words in PDF text layer: {pdf_words}")
    # tables and merged cells
    for i, t in enumerate(d.tables, 1):
        spans = len(t._tbl.findall(".//" + qn("w:gridSpan")))
        vmerge = len(t._tbl.findall(".//" + qn("w:vMerge")))
        print(f"table {i}: {len(t.rows)} rows x {len(t.columns)} grid columns, "
              f"horizontally merged cells: {spans}, vertical merges: {vmerge}")
    # section columns
    for i, s in enumerate(body.iter(qn("w:sectPr")), 1):
        cols = s.find(qn("w:cols"))
        n = cols.get(qn("w:num")) if cols is not None else None
        print(f"section {i}: Word column setting = {n or 1}")
    # headers, footers, footnotes as real Word parts
    with zipfile.ZipFile(docx_path) as z:
        names = z.namelist()
        # Separator and continuation entries carry w:type; real footnotes do not.
        fn = "word/footnotes.xml" in names and len(
            [t for t in re.findall(rb"<w:footnote(?:\s[^>]*)?>", z.read("word/footnotes.xml")) if b"w:type=" not in t]
        ) or 0
        print(f"real Word footnotes: {fn}")
        hdr = [n for n in names if re.match(r"word/(header|footer)\d*\.xml", n)]
        hdr_text = [n for n in hdr if re.sub(rb"<[^>]+>", b"", z.read(n)).strip()]
        print(f"header/footer parts with text: {len(hdr_text)}")
    # leftovers worth checking by hand
    page_lines = [p.text for p in paras if re.fullmatch(r"\s*(Page\s*)?\d+\s*", p.text)]
    print(f"body paragraphs that look like page numbers: {len(page_lines)}")
    breaks = sum(len(p._p.findall(".//" + qn("w:br"))) for p in paras)
    print(f"manual line breaks inside paragraphs: {breaks}")
    hyph = [m.group(0).replace("\n", "|") for p in paras for m in re.finditer(r"\w+-\s*\n\s*\w+", p.text)]
    print(f"words split by a hyphen and a line break: {hyph[:5]}")
    sizes = sorted({r.font.size.pt for p in d.paragraphs for r in p.runs if r.font.size})
    print(f"font sizes used (pt): {sizes}")
    small = sum(1 for p in d.paragraphs if any(r.font.size and r.font.size.pt < 8 for r in p.runs))
    print(f"paragraphs with text under 8 pt: {small}")
    floating = len(body.findall(".//" + qn("w:framePr"))) + len(body.findall(".//" + qn("wp:anchor")))
    print(f"frames or floating objects: {floating}")

if __name__ == "__main__":
    audit(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
