from pathlib import Path
import sys,uno
from check_uno import connect,prop

ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'ESP_00VB_Livrables'
PREVIEW=ROOT/'_fabrication_00VB'/'rendus'
PREVIEW.mkdir(exist_ok=True)
desktop=connect()
for arg in sys.argv[1:]:
    path=Path(arg).resolve()
    try:
        doc=desktop.loadComponentFromURL(path.as_uri(),'_blank',0,(prop('Hidden',True),prop('ReadOnly',True),prop('UpdateDocMode',0)))
        if doc is None:raise RuntimeError('Ouverture impossible')
        # Only update non-linked report/guide cross-references, never claim native Word execution.
        if path.name.startswith(('01_','02_','10_','11_')):
            try:
                doc.TextFields.refresh()
                indexes=doc.getDocumentIndexes()
                for i in range(indexes.Count):indexes.getByIndex(i).update()
            except Exception:pass
        dest=PREVIEW/(path.stem+'.pdf')
        filt='impress_pdf_Export' if path.suffix=='.pptx' else 'writer_pdf_Export'
        doc.storeToURL(dest.as_uri(),(prop('FilterName',filt),prop('Overwrite',True)))
        doc.close(True)
        print(str(dest),flush=True)
    except Exception as e:print('ERROR '+path.name+': '+str(e),flush=True)
