#!/usr/bin/env python3
"""Structural check of a returned .docx against ground-truth.md. Needs python-docx.
   python check_docx.py returned/<tool>.docx [--dump]"""
import re, sys
from docx import Document
path = sys.argv[1]; dump = "--dump" in sys.argv
d = Document(path)
paras = [p for p in d.paragraphs]
sname = lambda p: (p.style.name if p.style is not None else "")  # a docx built by hand may leave paragraphs with no style
heads = [(sname(p), p.text.strip()) for p in paras if sname(p).lower().startswith("heading") and p.text.strip()]
text = "\n".join(p.text for p in paras)
for t in d.tables:
    for r in t.rows:
        text += "\n" + "\t".join(c.text for c in r.cells)
xml = d.element.xml
toc_field = ("TOC \\" in xml) or ('docPartGallery w:val="Table of Contents"' in xml)
contents_list = bool(re.search(r"^\s*(table of )?contents\s*$", text, re.I | re.M))
typos = ["recieve", "seperate", "adress", "wich", "occassionally", "untill", "definately", "guarentee"]
left = [t for t in typos if re.search(r"\b" + t + r"\b", text, re.I)]
dup = text.lower().count("shipping is free on orders over €60")
prices = ["4.90", "6.90", "9.90", "7.90", "11.90", "16.90", "8.90", "12.90", "18.90", "26.90"]
tables = [(len(t.rows), len(t.columns)) for t in d.tables]
table_text = "\n".join("\t".join(c.text for c in r.cells) for t in d.tables for r in t.rows)
prices_in_table = sum(1 for p in prices if p in table_text)
facts = {"€60": r"€\s?60\b|60\s?€|60 euros", "14:00": r"14:00|2 ?pm", "2 to 3 days": r"2\s*(to|-|–)\s*3 working days", "5 to 7": r"5\s*(to|-|–)\s*7 working days",
         "3 to 5": r"3\s*(to|-|–)\s*5 working days", "4 to 8": r"4\s*(to|-|–)\s*8 working days", "14 days": r"\b14 days\b", "5 working days refund": r"5 working days",
         "48 hours": r"48 hours", "10:00 to 18:00": r"10:00\s*(to|-|–)\s*18:00", "one working day": r"(one|1) working day\b", "phone": r"\+351 210 000 000"}
facts_ok = [k for k, v in facts.items() if re.search(v, text, re.I)]
dates = set(re.findall(r"1 July 2026|07/01/2026|2026-07-01|1st July 2026|July 1, 2026", text))
print(f"headings: {len(heads)} -> {[h[1][:28] for h in heads]}")
print(f"heading numbering: {[re.match(r'\s*([0-9]+|[IVX]+)[.)]?\s', h[1]).group(1) if re.match(r'\s*([0-9]+|[IVX]+)[.)]?\s', h[1]) else '-' for h in heads]}")
print(f"tables: {tables} | prices in a table: {prices_in_table} of 10 distinct")
print(f"toc field: {toc_field} | contents list: {contents_list}")
print(f"typos left: {len(left)} of 8 -> {left}")
print(f"free-shipping paragraph occurs: {dup} (1 is right)")
print(f"facts: {len(facts_ok)} of 12 | missing: {[k for k in facts if k not in facts_ok]}")
print(f"date forms present: {sorted(dates)}")
print(f"words: {len(text.split())} (draft ~600)")
if dump:
    print("=====")
    for p in paras: print(f"[{sname(p)}] {p.text}")
    for t in d.tables:
        print("--- table")
        for r in t.rows: print(" | ".join(c.text for c in r.cells))
