#!/usr/bin/env python3
"""Synthetic DOCX -> LibreOffice DOCX semantic round-trip; no Word comparison."""
import argparse, hashlib, json, os, platform, subprocess, sys, tempfile
from pathlib import Path
from zipfile import ZipFile
from xml.etree import ElementTree as ET
from importlib.metadata import version
from docx import Document
from docx.shared import Mm
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.opc.constants import RELATIONSHIP_TYPE as RT

W='{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
R='{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
P='{http://schemas.openxmlformats.org/package/2006/relationships}'

def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest()
def fixture(path):
    d=Document(); sec=d.sections[0]; sec.page_width=Mm(210); sec.page_height=Mm(297)
    sec.left_margin=Mm(22); sec.right_margin=Mm(24)
    d.add_heading('Revue synthétique',level=1)
    p=d.add_paragraph('Échéance : 28 novembre — coût 1 234,50 € ; Ω. ')
    p.add_run('GRAS').bold=True; p.add_run(' ITALIQUE').italic=True
    p=d.add_paragraph('Lien : '); h=OxmlElement('w:hyperlink'); h.set(qn('r:id'),p.part.relate_to('https://example.org/controle',RT.HYPERLINK,is_external=True)); r=OxmlElement('w:r'); t=OxmlElement('w:t'); t.text='Documentation'; r.append(t); h.append(r); p._p.append(h)
    t=d.add_table(rows=2,cols=2); t.style='Table Grid';
    for cell,val in zip([c for row in t.rows for c in row.cells],['Produit','Quantité','Alpha','42']): cell.text=val
    d.add_paragraph('Premier élément',style='List Bullet'); d.add_paragraph('Second élément',style='List Bullet')
    sec.header.paragraphs[0].text='RECHERCHE — SYNTHÉTIQUE'; f=sec.footer.paragraphs[0]; f.add_run('Page '); field=OxmlElement('w:fldSimple'); field.set(qn('w:instr'),'PAGE'); f._p.append(field)
    d.add_page_break(); d.add_paragraph('FIN DU DOCUMENT'); d.core_properties.title='Fixture synthétique'; d.save(path)

def snapshot(path):
    with ZipFile(path) as z:
        def read(name): return ET.fromstring(z.read(name))
        def txt(el): return ''.join(t.text or '' for t in el.iter(W+'t'))
        doc=read('word/document.xml'); rel=read('word/_rels/document.xml.rels'); rels={r.get('Id'):r for r in rel}
        paragraphs=[txt(p) for p in doc.iter(W+'p') if txt(p)]
        table=[[txt(c) for c in row.findall(W+'tc')] for row in doc.iter(W+'tr')]
        links=[(txt(h),rels[h.get(R+'id')].get('Target')) for h in doc.iter(W+'hyperlink') if h.get(R+'id') in rels]
        def run_has(token,prop):
            return any(token in txt(r) and r.find(W+'rPr/'+W+prop) is not None and r.find(W+'rPr/'+W+prop).get(W+'val','1') not in ('0','false','off') for r in doc.iter(W+'r'))
        sect=doc.find('.//'+W+'sectPr'); margins=sect.find(W+'pgMar'); size=sect.find(W+'pgSz')
        default_header=next((e for e in sect.findall(W+'headerReference') if e.get(W+'type')=='default'),None)
        hdr=txt(read('word/'+rels[default_header.get(R+'id')].get('Target'))) if default_header is not None else ''
        footer=[read(n) for n in z.namelist() if n.startswith('word/footer') and n.endswith('.xml')]
        field_instructions=[(e.text or '').strip() for f in footer for e in f.iter(W+'instrText')]+[(e.get(W+'instr') or '').strip() for f in footer for e in f.iter(W+'fldSimple')]
        styles=read('word/styles.xml'); heading_ids={x.get(W+'styleId') for x in styles.iter(W+'style') if (x.find(W+'name') is not None and x.find(W+'name').get(W+'val','').lower() in ('heading 1','heading1'))}
        heading=any(txt(p)=='Revue synthétique' and p.find(W+'pPr/'+W+'pStyle') is not None and p.find(W+'pPr/'+W+'pStyle').get(W+'val') in heading_ids for p in doc.iter(W+'p'))
        # Explicit break encoding may differ: this is a structural probe, not a visual test.
        breaks=sum(e.get(W+'type')=='page' for e in doc.iter(W+'br'))+sum(e.get(W+'val','1') not in ('0','false','off') for e in doc.iter(W+'pageBreakBefore'))
        return {'body_text':paragraphs,'table_cells':table,'hyperlinks':links,'bold':run_has('GRAS','b'),'italic':run_has('ITALIQUE','i'),'heading_style':heading,'page_width_twips':int(size.get(W+'w')),'page_height_twips':int(size.get(W+'h')),'left_margin_twips':int(margins.get(W+'left')),'right_margin_twips':int(margins.get(W+'right')),'header_text':hdr,'page_field':any(x.split()[0]=='PAGE' for x in field_instructions if x),'explicit_page_breaks':breaks}

def run(root,lo):
    root.mkdir(parents=True,exist_ok=True); src=root/'fixture.docx'; fixture(src); baseline=snapshot(src)
    expected={'body_text':['Revue synthétique','Échéance : 28 novembre — coût 1 234,50 € ; Ω. GRAS ITALIQUE','Lien : Documentation','Produit','Quantité','Alpha','42','Premier élément','Second élément','FIN DU DOCUMENT'],'table_cells':[['Produit','Quantité'],['Alpha','42']],'hyperlinks':[('Documentation','https://example.org/controle')],'bold':True,'italic':True,'heading_style':True,'page_width_twips':11906,'page_height_twips':16838,'left_margin_twips':1247,'right_margin_twips':1361,'header_text':'RECHERCHE — SYNTHÉTIQUE','page_field':True,'explicit_page_breaks':1}
    if baseline!=expected: raise AssertionError(f'Fixture unexpectedly differs: {baseline!r}')
    runs=[]
    for i in range(1,3):
        out=root/f'run-{i}'; out.mkdir(exist_ok=True)
        with tempfile.TemporaryDirectory() as profile:
            p=subprocess.run([lo,'-env:UserInstallation='+Path(profile).as_uri(),'--headless','--convert-to','docx:Office Open XML Text','--outdir',str(out.resolve()),str(src.resolve())],capture_output=True,text=True,timeout=60,check=True)
        target=out/src.name
        if not target.is_file(): raise RuntimeError(p.stdout+p.stderr)
        actual=snapshot(target); checks=[]
        for k,e in expected.items():
            v=actual[k]; tolerance=2 if k.endswith('_twips') else 0
            ok=abs(v-e)<=tolerance if tolerance else v==e
            checks.append({'id':k,'expected':e,'observed':v,'tolerance':tolerance,'status':'pass' if ok else 'difference'})
        runs.append({'run':i,'output_sha256':sha(target),'checks':checks,'stdout':p.stdout.strip()})
    report={'schema_version':'1.0','protocol':'DOCX-LO-RT-001','engine':subprocess.check_output([lo,'--version'],text=True).strip(),'platform':platform.platform(),'python':platform.python_version(),'python_docx':version('python-docx'),'source_sha256':sha(src),'runs':runs,'limits':['Synthetic document only, created with python-docx, not Microsoft Word.','Semantic OOXML probes only; no rendering, visual fidelity, macros, digital signatures, tracked changes, or collaboration assessed.','Two fresh profiles in one environment; no independent replication.','Explicit structural page-break probe does not establish visual pagination.','2 twips tolerance for page dimensions and margins.','Header probe checks the default referenced header only, not first/even page behavior.']}
    (root/'results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
    print(json.dumps({'engine':report['engine'],'checks_per_run':len(expected),'runs':[{ 'run':r['run'],'pass':sum(c['status']=='pass' for c in r['checks']),'differences':[c for c in r['checks'] if c['status']!='pass']} for r in runs]},ensure_ascii=False,indent=2))
if __name__=='__main__':
    ap=argparse.ArgumentParser(); ap.add_argument('--out',type=Path,required=True); ap.add_argument('--lo',default='libreoffice'); a=ap.parse_args(); run(a.out,a.lo)
