"""Separate desktop reader for actual RTF outputs; no browser/app self round trip."""
from pathlib import Path
import datetime,hashlib,json,subprocess,sys,tempfile
folder=Path(sys.argv[1]).resolve();out=Path(sys.argv[2]).resolve()
assert not out.exists(),'Never overwrite retained reader output';out.mkdir()
files=sorted(folder.glob('*.rtf'));assert len(files)==18,'All18 final RTF outputs required'
binary=Path.home()/'.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/override/soffice'
sha=lambda b:hashlib.sha256(b).hexdigest()
version=subprocess.run([str(binary),'--version'],capture_output=True,timeout=30)
with tempfile.TemporaryDirectory(prefix='tabmorph-static-word-rtf-reader-') as profile:
    args=[str(binary),'-env:UserInstallation='+Path(profile).as_uri(),'--headless','--norestore','--nodefault','--nofirststartwizard','--convert-to','docx','--outdir',str(out),*[str(p) for p in files]]
    result=subprocess.run(args,capture_output=True,timeout=240)
(out/'stdout.txt').write_bytes(result.stdout);(out/'stderr.txt').write_bytes(result.stderr)
rows=[]
for source in files:
    target=out/(source.stem+'.docx')
    rows.append(dict(input=source.name,inputSha256=sha(source.read_bytes()),output=target.name,outputExists=target.exists(),outputSha256=sha(target.read_bytes()) if target.exists() else None))
report=dict(checkedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),complete=result.returncode==0 and all(r['outputExists'] for r in rows),files=len(rows),exitCode=result.returncode,readerVersion=version.stdout.decode(errors='replace'),reader=str(binary),arguments=args,rows=rows,scope='Independent installed desktop import to readable DOCX. Separate version of same LibreOffice upstream family; not an independent rendering truth or competitive-quality oracle. Original RTF outputs remain unchanged.')
(out/'reader.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(dict(complete=report['complete'],files=len(rows),exitCode=result.returncode)))
assert report['complete'],'Retained RTF desktop reader failure'
