"""Same-input DOCX→RTF note/comment checks, including retained production98 failures."""
from pathlib import Path
import datetime,hashlib,json,subprocess,sys,tempfile
from static_word_readers import source_features,norm

folder=Path(sys.argv[1]).resolve();out=Path(sys.argv[2]).resolve()
assert not out.exists(),'Never overwrite retained comparison';out.mkdir()
meta=[json.loads(p.read_text()) for p in sorted(folder.glob('*.json'))]
meta=[r for r in meta if r.get('to')=='rtf'];assert len(meta)==6,'Six actual DOCX→RTF files required'
sha=lambda b:hashlib.sha256(b).hexdigest()
for r in meta:
    assert sha((folder/r['file']).read_bytes())==r['sha256']
    assert sha(Path(r['source']).read_bytes())==r['sourceSha256']
binary=Path.home()/'.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/override/soffice'
with tempfile.TemporaryDirectory(prefix='tabmorph-rtf-regression-reader-') as profile:
    args=[str(binary),'-env:UserInstallation='+Path(profile).as_uri(),'--headless','--norestore','--nodefault','--nofirststartwizard','--convert-to','docx','--outdir',str(out),*[str(folder/r['file']) for r in meta]]
    process=subprocess.run(args,capture_output=True,timeout=180)
(out/'stdout.txt').write_bytes(process.stdout);(out/'stderr.txt').write_bytes(process.stderr)
checks=[];rows=[]
for r in meta:
    decoded=out/(Path(r['file']).stem+'.docx');assert decoded.exists(),'Reader output missing'
    original=source_features(Path(r['source']));actual=source_features(decoded)
    observations=[('title',norm(original['metadata']['title'] or ''),norm(actual['metadata']['title'] or '')),
                  ('original author',norm(original['metadata']['creator'] or ''),norm(actual['metadata']['creator'] or '')),
                  ('typed referenced note bodies and order',original['referenceOrder'],actual['referenceOrder']),
                  ('main-story comment body author and range',[(c['text'],c['author'],c['rangeText']) for c in original['comments']],[(c['text'],c['author'],c['rangeText']) for c in actual['comments']])]
    for control,expected,value in observations:checks.append(dict(file=r['file'],control=control,expected=expected,actual=value,passed=expected==value))
    rows.append(dict(file=r['file'],bytes=(folder/r['file']).stat().st_size,sha256=r['sha256'],source=r['source'],sourceSha256=r['sourceSha256'],decoded=decoded.name,decodedSha256=sha(decoded.read_bytes())))
report=dict(readAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),complete=process.returncode==0 and len(rows)==6,files=len(rows),observations=len(checks),failures=[c for c in checks if not c['passed']],checks=checks,rows=rows,readerExitCode=process.returncode,arguments=args,
            goalComplete=False,competitiveQuality='UNVERIFIED',scope='Original source versus actual same-input production98 or current DOCX→RTF outputs. Separate LibreOfficeDev26.8 import plus ZIP/lxml. Failing before98 controls remain failed; current output must pass. No claim about unmarked edge-space semantics, arbitrary rendering, DOC/ODT input profiles or CloudConvert parity.')
(out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
print(json.dumps(dict(complete=report['complete'],files=len(rows),observations=len(checks),failed=len(report['failures']))))
assert report['complete'],'Retained reader failure'
