"""Independent actual-file readers; no Tabmorph parser/writer is imported."""
from pathlib import Path
from zipfile import ZipFile
from lxml import etree as E
from PIL import Image
import argparse,datetime,hashlib,io,json,re,subprocess,tempfile
import pypdf,pdfplumber

ap=argparse.ArgumentParser();ap.add_argument('folder');ap.add_argument('out');args=ap.parse_args();base=Path(args.folder);out=Path(args.out);out.mkdir(exist_ok=False);native=out/'native';native.mkdir()
sha=lambda b:hashlib.sha256(b).hexdigest();fixtures=Path('benchmarks/fixtures/text-office1');manifestBytes=(fixtures/'manifest.json').read_bytes();manifest=json.loads(manifestBytes);inputs={r['name']:r for r in manifest['rows']}
for r in inputs.values():assert sha((fixtures/r['file']).read_bytes())==r['sha256']
expected={browser+'-'+r['name']+'.'+ext for browser in ['chromium','webkit']for r in inputs.values()for ext in [*r['newTargets'],'odt']}|{browser+'-'+name+'.'+ext for browser in ['chromium','webkit']for name,ext in [('recovered','doc'),('cancel-recovered','rtf'),('embedded','pdf')]}
actual={p.name for p in base.iterdir()if p.suffix in ['.doc','.rtf','.pdf','.odt']};assert actual==expected,{'missing':sorted(expected-actual),'unexpected':sorted(actual-expected)}
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'))
ns={k:'urn:oasis:names:tc:opendocument:xmlns:'+v+':1.0'for k,v in [('o','office'),('s','style'),('t','text'),('ta','table'),('d','drawing'),('fo','xsl-fo-compatible')]};ns.update(x='http://www.w3.org/1999/xlink',dc='http://purl.org/dc/elements/1.1/')
exe='/Users/gregorythompson/.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/override/soffice';poppler=Path('/Users/gregorythompson/.cache/codex-runtimes/codex-primary-runtime/dependencies/native/poppler/poppler/bin');checks=[];rows=[];logs=[]
def check(file,name,ok,details=None,secondary=False):
 r=dict(file=file.name,check=name,passed=bool(ok),secondaryReaderDifference=bool(secondary and not ok))
 if details is not None:r['details']=details
 checks.append(r)
def compact(s):return re.sub(r'\s','',s)
labels={'semantic':[('3','Start at three'),('4','Continue at four'),('9','Ninth item')],'holdout':[('27','Ordinal twenty-seven'),('31','Ordinal thirty-one')]}
def without_labels(s,corpus):
 # Only exact authored list labels before their exact source text may be
 # removed for body comparison. Their actual presence is separately required.
 for number,text in labels.get(corpus,[]):s=re.sub(r'(?m)^[ \t]*'+number+r'\.[ \t]*(?='+re.escape(text)+')','',s)
 s=re.sub(r'(?m)^[ \t]*[•·◦][ \t]*(?=Nested bullet)','',s)
 return s
def odttext(n):
 tag=E.QName(n).localname
 if tag=='frame':return ''
 if tag=='s':return ' '*int(n.get('{'+ns['t']+'}c','1'))
 if tag=='tab':return '\t'
 if tag=='line-break':return '\n'
 return(n.text or '')+''.join(odttext(c)+(c.tail or '')for c in n)
def pixels(raw):
 im=Image.open(io.BytesIO(raw)).convert('RGB');return im.size,im.tobytes()
def literal_check(file,text,intent,reader):
 expected=intent['exactLfText'];actual=text.replace('\r\n','\n').replace('\r','\n')
 # Cocoa serializes soft breaks as its documented U+2028 line separator.
 # Retain the raw text, count every such separator, and map only this reader's
 # line token. Never collapse spaces, tabs, empty lines or paragraph boundaries.
 if reader=='Cocoa':actual=actual.replace('\u2028','\n')
 check(file,reader+' literal spaces/tabs/blank lines and Unicode',actual==expected or actual==expected+'\n',dict(expected=expected,actual=actual,rawReaderText=text,cocoaLineSeparators=text.count('\u2028'),extraFinalParagraphSeparator=actual==expected+'\n',limit='Cocoa U+2028 soft-line serialization and at most one final paragraph separator; exact remaining text, spaces, tabs and line counts. Raw reader text is retained.'))

def pdf_images(reader):
 result=[]
 for page in reader.pages:
  for ref in page['/Resources'].get('/XObject',{}).values():
   image=ref.get_object()
   if image.get('/Subtype')!='/Image':continue
   size=(int(image['/Width']),int(image['/Height']));filters=image.get('/Filter');raw=image.get_data()
   if filters=='/DCTDecode':
    # Read the actual encoded JPEG stream. Page.images exports a new JPEG
    # through Pillow.save(), introducing a second generation absent from PDF.
    decodedSize,rgb=pixels(raw);assert decodedSize==size
   else:
    assert image.get('/ColorSpace')=='/DeviceRGB'and image.get('/BitsPerComponent')==8 and not image.get('/SMask'),'Unexpected fixture PDF image profile'
    assert len(raw)==size[0]*size[1]*3;rgb=raw
   result.append((size,rgb))
 return result
with tempfile.TemporaryDirectory(prefix='tabmorph-text-office-reader-')as profile:
 for index,file in enumerate(sorted(base.iterdir())):
  if file.name not in expected:continue
  name=file.stem.split('-',1)[1];name='semantic'if name in ['recovered','cancel-recovered','embedded']else name;intent=inputs[name];corpus=name.split('-utf16')[0];data=file.read_bytes();wanted=compact(''.join(intent['orderedText']));folder=native/str(index);folder.mkdir();row=dict(file=file.name,bytes=len(data),sha256=sha(data),source=intent['file'],sourceSha256=intent['sha256'],originalCorpus=intent['originalCorpus'],newOperation=file.suffix[1:]in intent['newTargets'])
  if file.suffix=='.odt':
   z=ZipFile(file);check(file,'ODF ZIP CRC, unique names 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 n in ['content.xml','styles.xml','meta.xml','META-INF/manifest.xml']:
    doc=E.fromstring(z.read(n),E.XMLParser(resolve_entities=False,no_network=True));docs[n]=doc;validator=ms if n.endswith('manifest.xml')else schema;ok=validator.validate(doc);check(file,'official ODF1.3 schema '+n,ok,None if ok else str(validator.error_log))
   body=docs['content.xml'].find('o:body/o:text',ns);bodytext=odttext(body);check(file,'all source body characters and order in ODF',compact(bodytext)==wanted,dict(expected=wanted,actual=compact(bodytext)))
   if corpus=='literal':check(file,'exact original literal ODF whitespace',bodytext==intent['exactLfText'],dict(expected=intent['exactLfText'],actual=bodytext))
   check(file,'source filename title metadata',docs['meta.xml'].findtext('.//dc:title',namespaces=ns)==name)
   check(file,'original embedded raster bytes in ODF',{sha(z.read(n))for n in z.namelist()if n.startswith('Pictures/')}=={sha((fixtures/n).read_bytes())for n in intent['images']})
   if corpus=='semantic':check(file,'ODF positive list starts3 and9',all(docs['content.xml'].xpath('//t:list-item[@t:start-value="'+n+'"]',namespaces=ns)for n in ['3','9']))
   if corpus=='holdout':check(file,'ODF source row/column merges',bool(docs['content.xml'].xpath('//ta:table-cell[@ta:number-rows-spanned="2"]',namespaces=ns))and bool(docs['content.xml'].xpath('//ta:table-cell[@ta:number-columns-spanned="2"]',namespaces=ns)))
  elif file.suffix=='.doc':check(file,'actual binary DOC compound signature',data.startswith(bytes.fromhex('d0cf11e0a1b11ae1')))
  elif file.suffix=='.rtf':check(file,'complete RTF signature and final group',data.startswith(b'{\\rtf1')and data.rstrip().endswith(b'}'))
  if file.suffix in ['.doc','.rtf']:
   cocoa=subprocess.run(['/usr/bin/textutil','-convert','txt','-encoding','UTF-8','-stdout',str(file)],capture_output=True,timeout=60);text=cocoa.stdout.decode('utf-8-sig',errors='strict');(folder/'cocoa.txt').write_text(text);logs.append(dict(file=file.name,reader='Cocoa TextEdit attributed-string import',exit=cocoa.returncode,stderr=cocoa.stderr.decode(errors='replace')));check(file,'independent Cocoa imports actual file',cocoa.returncode==0)
   if corpus=='literal':literal_check(file,text,intent,'Cocoa')
   else:
    same=compact(without_labels(text,corpus))==wanted;known=False
    if not same and file.suffix=='.doc':
     instruction=' HYPERLINK "https://example.invalid/manual"'if corpus=='semantic'else' HYPERLINK  \\l "bookmark-1"'
     known=text.count(instruction)==1 and compact(without_labels(text.replace(instruction,'',1),corpus))==wanted
    # This deliberately remains a failed secondary-reader observation. No
    # instruction is removed from the stored output or counted as a pass.
    check(file,'Cocoa source body characters and order',same,dict(expected=wanted,actual=compact(without_labels(text,corpus)),raw=text,knownDocFieldInstructionDifference=known),secondary=known)
  pdf=file
  if file.suffix!='.pdf':
   common=[exe,'-env:UserInstallation='+Path(profile).as_uri(),'--headless','--convert-to'];cmd=common+['txt:Text (encoded):UTF8','--outdir',str(folder),str(file)];r=subprocess.run(cmd,capture_output=True,text=True,timeout=120);logs.append(dict(file=file.name,reader='stock LibreOffice TXT',exit=r.returncode,stdout=r.stdout,stderr=r.stderr));textfile=folder/(file.stem+'.txt');check(file,'stock native reader imports and extracts',r.returncode==0 and textfile.exists())
   if textfile.exists():
    text=textfile.read_text(encoding='utf-8-sig');check(file,'native exact source body characters and order',compact(without_labels(text,corpus))==wanted,dict(expected=wanted,actual=compact(without_labels(text,corpus)),raw=text))
    if corpus=='literal':literal_check(file,text,intent,'Native TXT')
    if corpus=='semantic':check(file,'native literal code whitespace', '  code  spaces\tcolumn\nsecond <line> &copy;'in text,dict(raw=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(file)],capture_output=True,text=True,timeout=120);logs.append(dict(file=file.name,reader='stock native PDF import',exit=r.returncode,stdout=r.stdout,stderr=r.stderr));pdf=folder/(file.stem+'.pdf');check(file,'stock native reader prints actual file',r.returncode==0 and pdf.exists())
   if not pdf.exists():rows.append(row);continue
  reader=pypdf.PdfReader(pdf);raw=''.join(p.extract_text()or''for p in reader.pages);display=subprocess.check_output([str(poppler/'pdftotext'),'-layout',str(pdf),'-'],text=True);(folder/'pypdf.txt').write_text(raw);(folder/'poppler.txt').write_text(display);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],rawPdfTextMatchesSource=compact(without_labels(raw,corpus))==wanted,popplerTextMatchesSource=compact(without_labels(display,corpus))==wanted)
  check(file,'finite complete PDF pages',not reader.is_encrypted and 0<len(reader.pages)<100 and all(0<float(p.mediabox.width)<2000 and 0<float(p.mediabox.height)<2000 for p in reader.pages))
  if file.suffix=='.pdf':check(file,'actual PDF exact logical source body characters and order',row['rawPdfTextMatchesSource'],dict(expected=wanted,actual=compact(without_labels(raw,corpus)),raw=raw))
  rendered=pdf_images(reader);expectedPictures=[pixels((fixtures/n).read_bytes())for n in intent['images']]
  check(file,'all original raster dimensions retained',sorted(size for size,_ in rendered)==sorted(size for size,_ in expectedPictures))
  for size,picture in expectedPictures:
   candidates=[p for s,p in rendered if s==size];error=min((max(abs(a-b)for a,b in zip(picture,p))if len(p)==len(picture)else 999 for p in candidates),default=999);check(file,'full original raster pixels '+str(size),error<=1,dict(maximumRgbError=error,limit=1,method='Original opaque RGB pixels against independent decoded full image. No resampling, alignment, normalization or cropping. JPEG native-decoder rounding allowed at most1 code value.'))
  with pdfplumber.open(pdf)as p:
   chars=[c for page in p.pages for c in page.chars];plain=''.join(c['text']for c in chars)
   def run(text):
    i=plain.find(text);return chars[i:i+len(text)]if i>=0 else[]
   if corpus=='semantic':
    for word,style in [('bold control','bold'),('italic control','italic')]:
     glyphs=run(word);check(file,'rendered '+style+' '+word,bool(glyphs)and all(style in c['fontname'].lower()or style=='italic'and'oblique'in c['fontname'].lower()for c in glyphs),[c['fontname']for c in glyphs])
    for value,direction in [('H2O',-1),('x2',1)]:
     c=run(value);check(file,'rendered source script baseline '+value,bool(c)and len(c)==len(value)and(c[1]['matrix'][5]-c[0]['matrix'][5])*direction>1 and c[1]['size']<c[0]['size'],[{k:x[k]for k in ['text','size','matrix','y0']}for x in c])
   if corpus in labels:
    for number,text in labels[corpus]:check(file,'visible original ordinal '+number,bool(re.search(r'(?m)^\s*'+number+r'\.\s*'+re.escape(text),display)),dict(text=display))
  if file.suffix=='.pdf':
   r=subprocess.run([str(poppler/'pdftoppm'),'-r','96','-png','-singlefile',str(pdf),str(folder/'first-page')],capture_output=True,timeout=120);check(file,'independent full first-page raster render',r.returncode==0 and(folder/'first-page.png').exists())
   if(folder/'first-page.png').exists():row['firstPagePng']=dict(path=str(folder/'first-page.png'),sha256=sha((folder/'first-page.png').read_bytes()))
  row['metadata']=dict(reader.metadata or{});rows.append(row)
report=dict(checkedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),completeScope=True,actualFiles=len(rows),newOperationFiles=sum(r['newOperation']for r in rows),existingOdtSourceControls=sum(not r['newOperation']for r in rows),originalCorpora=3,encodingDerivatives=2,rows=rows,checks=checks,failures=[r for r in checks if not r['passed']],requiredFailures=[r for r in checks if not r['passed']and not r['secondaryReaderDifference']],secondaryReaderDifferences=[r for r in checks if r['secondaryReaderDifference']],nativeLogs=logs,fixtureManifestSha256=sha(manifestBytes),producerSha256=sha(Path(__file__).read_bytes()),nativeReader=subprocess.check_output([exe,'--version'],text=True).strip(),cocoaReader='macOS textutil / independent attributed-string DOC and RTF import',popplerVersion=subprocess.run([str(poppler/'pdftotext'),'-v'],capture_output=True,text=True).stderr,method='Authored intent and independent ODF1.3 RNG/ZIP/XML, Cocoa, stock Office, Poppler, pypdf, PDFMiner and Pillow readers. Exact source text order is primary; only authored list labels are removed and actual ordinals separately required. Literal whitespace is exact with explicitly recorded Cocoa U+2028 soft-line serialization and at most one independent final-paragraph separator. Raw reader data remains. Images decode directly from actual PDF streams; pypdf exported JPEGs are reader derivatives and not the original image. Actual text matrices supply baselines; glyph bounding-box bottoms are not baselines. Cocoa DOC field-instruction exposure is a retained FAILED secondary-reader observation, never normalized into a pass. Native TXT, source ODF and actual new PDF logical text remain strict. Browser duplicates and derived reader PDFs are not additional corpora or comparative observations.',readerStandards=['https://developer.apple.com/documentation/appkit/nslineseparatorcharacter','https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-23/'],competitiveQuality='UNVERIFIED for new pairs; no same-input provider references or matched quality/size curves. Cocoa DOC hyperlink-field display differences remain open. Existing provider losses remain open.')
(out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2,default=str)+'\n');print(dict(files=len(rows),checks=len(checks),failures=len(report['failures']),requiredFailures=len(report['requiredFailures']),secondaryDifferences=len(report['secondaryReaderDifferences'])));raise SystemExit(bool(report['requiredFailures']))
