"""Independent source/ODF/PDF/Cocoa/Apache controls on actual browser downloads.
Stock LibreOffice import is additional reader evidence, not an independent exporter.
"""
from pathlib import Path
from zipfile import ZipFile
from lxml import etree as E,html
from PIL import Image
import pypdf
import json,hashlib,re,subprocess,tempfile,argparse,io,datetime
ap=argparse.ArgumentParser();ap.add_argument('folder');ap.add_argument('out');ap.add_argument('poi');a=ap.parse_args()
base=Path(a.folder);out=Path(a.out);out.mkdir(exist_ok=False);poi=Path(a.poi);fixtures=Path('benchmarks/fixtures/html-office1')
expected={b+'-'+n+'.'+t for b in ['chromium','webkit']for n in ['semantic','semantic-utf16le','holdout']for t in ['doc','rtf','pdf','odt']}|{b+'-'+n for b in ['chromium','webkit']for n in ['recovered.doc','embedded.pdf']}
assert {p.name for p in base.iterdir()}==expected
sha=lambda b:hashlib.sha256(b).hexdigest();checks=[];rows=[];logs=[]
def check(f,n,ok,details=None,secondary=False):
 checks.append(dict(file=f.name,check=n,passed=bool(ok),secondary=bool(secondary),details=details))
def compact(s):return re.sub(r'\s','',s)
def labels(s):
 for value,text in [('3','LIST THREE'),('7','LIST SEVEN')]:s=re.sub(r'(?m)^[ \t]*'+value+r'\.[ \t]*(?='+text+')','',s)
 return re.sub(r'(?m)^[ \t]*[•·◦\uf0b7][ \t]*(?=NESTED BULLET)','',s)
def source(n):
 b=(fixtures/(n+'.html')).read_bytes();s=b.decode('utf-16' if 'utf16' in n else 'utf-8');doc=html.document_fromstring(s)
 for bad in doc.xpath('//head|//script|//style|//iframe|//form|//video|//audio|//object|//embed'):
  bad.drop_tree()
 return compact(doc.find('body').text_content())
ns={k:'urn:oasis:names:tc:opendocument:xmlns:'+v+':1.0'for k,v in [('o','office'),('t','text'),('ta','table'),('d','drawing')]};ns['dc']='http://purl.org/dc/elements/1.1/'
def odttext(n):
 name=E.QName(n).localname
 if name=='frame':return ''
 if name=='s':return ' '*int(n.get('{'+ns['t']+'}c','1'))
 if name=='tab':return '\t'
 if name=='line-break':return '\n'
 return (n.text or '')+''.join(odttext(c)+(c.tail or '')for c in n)
schema=E.RelaxNG(E.parse('benchmarks/fixtures/odt-output/OpenDocument-v1.3-schema.rng'));ms=E.RelaxNG(E.parse('benchmarks/fixtures/odt-output/OpenDocument-v1.3-manifest-schema.rng'))
exe='/Users/gregorythompson/.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/override/soffice';pop='/Users/gregorythompson/.cache/codex-runtimes/codex-primary-runtime/dependencies/native/poppler/poppler/bin/'
original=Path('benchmarks/fixtures/text-office1/original.png').read_bytes();im=Image.open(io.BytesIO(original)).convert('RGB');picture=(im.size,im.tobytes())
with tempfile.TemporaryDirectory(prefix='html-office-reader-')as profile:
 for i,f in enumerate(sorted(base.iterdir())):
  n=f.stem.split('-',1)[1];n='semantic' if n in ['recovered','embedded']else n;semantic=n.startswith('semantic');wanted=source(n);folder=out/str(i);folder.mkdir();b=f.read_bytes();row=dict(file=f.name,bytes=len(b),sha256=sha(b),source=n+'.html',sourceSha256=sha((fixtures/(n+'.html')).read_bytes()),originalCorpus='semantic'if semantic else'holdout',encodingDerivative='utf16' in n,newOperation=f.suffix!='.odt')
  if f.suffix=='.odt':
   z=ZipFile(f);check(f,'ODF ZIP CRC, unique members and stored first mimetype',z.testzip()is None and len(z.namelist())==len(set(z.namelist()))and z.infolist()[0].filename=='mimetype'and z.infolist()[0].compress_type==0 and z.read('mimetype')==b'application/vnd.oasis.opendocument.text')
   docs={}
   for name in ['content.xml','styles.xml','meta.xml','META-INF/manifest.xml']:
    doc=E.fromstring(z.read(name),E.XMLParser(resolve_entities=False,no_network=True));docs[name]=doc;v=ms if name.endswith('manifest.xml')else schema;check(f,'official ODF1.3 schema '+name,v.validate(doc),str(v.error_log))
   text=odttext(docs['content.xml'].find('o:body/o:text',ns));check(f,'all source body characters and order in ODF',compact(text)==wanted,dict(expected=wanted,actual=compact(text)))
   check(f,'filename title and omitted HTML head title',docs['meta.xml'].findtext('.//dc:title',namespaces=ns)==n)
   check(f,'original packaged raster bytes',{sha(z.read(p))for p in z.namelist()if p.startswith('Pictures/')}==({sha(original)}if semantic else set()))
   if semantic:
    check(f,'explicit original preformatted spaces, tab and blank line','CODE <tag>\n  two spaces\tTAB\n\nFINAL CODE LINE'in text)
    check(f,'list starts3 and7 and merged table',all(docs['content.xml'].xpath('//t:list-item[@t:start-value="'+v+'"]',namespaces=ns)for v in ['3','7'])and bool(docs['content.xml'].xpath('//ta:table-cell[@ta:number-columns-spanned="2"]',namespaces=ns)))
  if f.suffix in ['.doc','.rtf']:
   r=subprocess.run(['/usr/bin/textutil','-convert','txt','-encoding','UTF-8','-stdout',str(f)],capture_output=True,timeout=60);text=r.stdout.decode('utf-8-sig');(folder/'cocoa.txt').write_text(text);check(f,'Cocoa imports actual file',r.returncode==0)
   # Known independent Cocoa binary-DOC field-display differences remain FAILED
   # secondary observations; never strip instructions to count a passing result.
   check(f,'Cocoa exact logical source body',compact(labels(text))==wanted,dict(expected=wanted,actual=compact(labels(text)),raw=text),secondary=f.suffix=='.doc' and semantic and text.count(' HYPERLINK "https://example.com/reference"')==1 and text.count(' HYPERLINK  \\l "bookmark-1"')==1 and compact(labels(text.replace(' HYPERLINK "https://example.com/reference"','',1).replace(' HYPERLINK  \\l "bookmark-1"','',1)))==wanted)
  if f.suffix=='.doc':
   check(f,'binary compound DOC signature',b.startswith(bytes.fromhex('d0cf11e0a1b11ae1')));p=poi/f.name;check(f,'Apache reader input whole-file SHA256',(p/'input.sha256').read_text()==sha(b));text=(p/'typed-field-results.txt').read_text();visible=text.replace('\x07','\t').replace('\x01','');check(f,'independent Apache typed-field results preserve all body characters and order',compact(visible)==wanted,dict(expected=wanted,actual=compact(visible)));fieldrows=(p/'fields.tsv').read_text().splitlines();check(f,'Apache actual field and image anchor counts',len(fieldrows)==(2 if semantic else 0) and text.count('\x01')==(1 if semantic else 0) and not re.search(r'[\x13-\x15]',visible))
   if semantic:
    import base64
    fields=[line.split('\t')for line in fieldrows];check(f,'Apache exact external/internal hyperlink instructions and display results',[(int(r[3]),base64.b64decode(r[4]).decode(),base64.b64decode(r[5]).decode())for r in fields]==[(88,' HYPERLINK "https://example.com/reference"\x01','MANUAL REFERENCE'),(88,' HYPERLINK  \\l "bookmark-1"\x01','FINISH LINK')])
    marks=[line.split('\t')for line in(p/'bookmarks.tsv').read_text().splitlines()];check(f,'Apache internal link has an actual bounded bookmark',any(base64.b64decode(r[0]).decode()=='bookmark-1' and 0<=int(r[1])<=int(r[2])<=len((p/'range-raw.txt').read_text())for r in marks))
    runs=[line.split('\t')for line in (p/'character-runs.tsv').read_text().splitlines()]
    check(f,'Apache bold and italic source runs',any('BOLD MARKER'in base64.b64decode(r[0]).decode()and r[1]=='true'for r in runs)and any('ITALIC MARKER'in base64.b64decode(r[0]).decode()and r[2]=='true'for r in runs))
    check(f,'Apache exact original embedded raster bytes',any(x.read_bytes()==original for x in p.glob('picture-*.bin')))
  pdf=f
  if f.suffix!='.pdf':
   common=[exe,'-env:UserInstallation='+Path(profile).as_uri(),'--headless','--convert-to'];r=subprocess.run(common+['txt:Text (encoded):UTF8','--outdir',str(folder),str(f)],capture_output=True,text=True,timeout=120);logs.append(dict(file=f.name,reader='stock native TXT',exit=r.returncode,stdout=r.stdout,stderr=r.stderr));p=folder/(f.stem+'.txt');check(f,'stock native text import',r.returncode==0 and p.exists())
   if p.exists():text=p.read_text(encoding='utf-8-sig');check(f,'stock native source body characters and order',compact(labels(text))==wanted,dict(expected=wanted,actual=compact(labels(text))))
   settings={'UseLosslessCompression':{'type':'boolean','value':'true'},'ReduceImageResolution':{'type':'boolean','value':'false'}};r=subprocess.run(common+['pdf:writer_pdf_Export:'+json.dumps(settings),'--outdir',str(folder),str(f)],capture_output=True,text=True,timeout=120);logs.append(dict(file=f.name,reader='stock native PDF',exit=r.returncode,stdout=r.stdout,stderr=r.stderr));pdf=folder/(f.stem+'.pdf');check(f,'stock native PDF import',r.returncode==0 and pdf.exists())
   if not pdf.exists():rows.append(row);continue
  reader=pypdf.PdfReader(pdf);text=''.join(p.extract_text()or''for p in reader.pages);(folder/'pypdf.txt').write_text(text);row.update(pdf=str(pdf),pdfSha256=sha(pdf.read_bytes()),pages=len(reader.pages),pageSizes=[[float(p.mediabox.width),float(p.mediabox.height)]for p in reader.pages]);check(f,'complete Letter pages',not reader.is_encrypted and 0<len(reader.pages)<30 and all(abs(float(p.mediabox.width)-612)<.1 and abs(float(p.mediabox.height)-792)<.1 for p in reader.pages))
  check(f,'PDF exact logical source body characters and order',compact(labels(text))==wanted,dict(expected=wanted,actual=compact(labels(text))))
  if f.suffix=='.pdf':
   display=subprocess.check_output([pop+'pdftotext','-layout',str(pdf),'-'],text=True);(folder/'poppler.txt').write_text(display);check(f,'independent Poppler source body characters and order',compact(labels(display))==wanted,dict(expected=wanted,actual=compact(labels(display))))
   if semantic:
    images=[]
    for p in reader.pages:
     for x in (p.get('/Resources',{}).get('/XObject',{})).values():
      obj=x.get_object()
      if obj.get('/Subtype')=='/Image':
       raw=obj.get_data();size=(int(obj['/Width']),int(obj['/Height']));images.append((size,raw))
    check(f,'actual PDF decoded original raster RGB and dimensions',picture in images)
   subprocess.run([pop+'pdftocairo','-png','-r','72',str(pdf),str(folder/'whole-page')],check=True,capture_output=True,timeout=120)
   row['wholePagePngs']=[dict(path=str(p),bytes=p.stat().st_size,sha256=sha(p.read_bytes()))for p in sorted(folder.glob('whole-page-*.png'))]
  rows.append(row)
report=dict(checkedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),completeScope=len(rows)==28,files=len(rows),newOperationFiles=sum(r['newOperation']for r in rows),originalCorpora=2,encodingDerivatives=1,rows=rows,checks=checks,failures=[c for c in checks if not c['passed']],requiredFailures=[c for c in checks if not c['passed']and not c['secondary']],failedSecondaryCocoaObservations=[c for c in checks if not c['passed']and c['secondary']],logs=logs,competitiveQuality='UNVERIFIED',goalComplete=False)
(out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n');print(dict(files=len(rows),controls=len(checks),requiredFailures=len(report['requiredFailures']),failedSecondary=len(report['failedSecondaryCocoaObservations'])));raise SystemExit(bool(report['requiredFailures']))
