"""Independent Apache POI HWPF evidence over actual binary DOC files."""
from pathlib import Path
from PIL import Image
import argparse,base64,datetime,hashlib,io,json,re
ap=argparse.ArgumentParser();ap.add_argument('downloads');ap.add_argument('reader');args=ap.parse_args();base=Path(args.downloads);reader=Path(args.reader);out=reader/'report.json';assert not out.exists();fixtures=Path('benchmarks/fixtures/text-office1');manifest=json.loads((fixtures/'manifest.json').read_text());inputs={r['name']:r for r in manifest['rows']};sha=lambda b:hashlib.sha256(b).hexdigest();checks=[];rows=[]
expected={browser+'-'+r['name']+'.doc'for browser in ['chromium','webkit']for r in inputs.values()}|{browser+'-recovered.doc'for browser in ['chromium','webkit']};assert{p.name for p in base.glob('*.doc')}==expected;assert{p.name for p in reader.iterdir()if p.is_dir()}==expected
def check(file,name,ok,details=None):
 item=dict(file=file.name,check=name,passed=bool(ok))
 if details is not None:item['details']=details
 checks.append(item)
def compact(s):return re.sub(r'\s','',s)
def pixels(raw):
 im=Image.open(io.BytesIO(raw)).convert('RGB');return(im.size,sha(im.tobytes()))
for file in sorted(base.glob('*.doc')):
 folder=reader/file.name;identity=file.stem.split('-',1)[1];intent=inputs['semantic'if identity=='recovered'else identity];corpus=intent['name'].split('-utf16')[0];data=file.read_bytes();assert(folder/'input.sha256').read_text()==sha(data)
 raw=(folder/'paragraphs-raw.txt').read_text();fields=(folder/'field-results.txt').read_text();converter=(folder/'converter-text.txt').read_text();pictures=sorted(folder.glob('picture-*.bin'));wanted=compact(''.join(intent['orderedText']))
 # Word text has typed cell delimiters(0x07), line breaks(0x0B), and picture
 # anchors(0x01). Their structures/counts are independently validated below.
 visible=fields.replace('\x07','\t').replace('\x0b','\n').replace('\x01','')
 check(file,'HWPF exact original body characters and order',compact(visible)==wanted,dict(expected=wanted,actual=compact(visible),rawDisplayResult=fields))
 check(file,'no residual field delimiters or unsupported control text',not re.search(r'[\x00-\x08\x0b\x0c\x0e-\x1f]',visible))
 check(file,'independent picture anchor count',fields.count('\x01')==len(intent['images']),dict(actual=fields.count('\x01'),expected=len(intent['images'])))
 if corpus=='literal':check(file,'HWPF exact source literal whitespace',visible==intent['exactLfText']or visible==intent['exactLfText']+'\n',dict(expected=intent['exactLfText'],actual=visible,extraFinalParagraphSeparator=visible==intent['exactLfText']+'\n'))
 else:
  check(file,'HWPF retains one bounded hyperlink field',raw.count('\x13')==raw.count('\x14')==raw.count('\x15')==1)
  if corpus=='semantic':check(file,'HWPF exact external hyperlink instruction and display result',' HYPERLINK "https://example.invalid/manual"\x01\x14Manual link\x15'in raw)
  else:check(file,'HWPF internal hyperlink display result and named target','HYPERLINK'in raw and'\\l "bookmark-1"'in raw and'\x14Return to target\x15'in raw)
 if corpus=='semantic':check(file,'HWPF exact literal code spaces/tab/line break','  code  spaces\tcolumn\nsecond <line> &copy;'in visible)
 bookmarks=[]
 for line in(folder/'bookmarks.tsv').read_text().splitlines():
  name,start,end=line.split('\t');bookmarks.append(dict(name=base64.b64decode(name).decode(),start=int(start),end=int(end)))
 if corpus=='holdout':check(file,'HWPF internal link resolves to actual bounded bookmark',any(b['name']=='bookmark-1'and 0<=b['start']<=b['end']<=len(raw)for b in bookmarks),bookmarks)
 runs=[]
 for line in(folder/'character-runs.tsv').read_text().splitlines():
  t,b,i,s,size,font=line.split('\t');runs.append(dict(text=base64.b64decode(t).decode(),bold=b=='true',italic=i=='true',script=int(s),halfPoints=int(size),font=base64.b64decode(font).decode()))
 if corpus=='semantic':
  for text,flag in [('bold control','bold'),('italic control','italic')]:check(file,'HWPF source '+flag+' character properties',any(text in r['text']and r[flag]for r in runs))
  check(file,'HWPF actual subscript and superscript properties',any('2'in r['text']and r['script']==2 for r in runs)and any('2'in r['text']and r['script']==1 for r in runs))
 elif corpus=='holdout':
  check(file,'HWPF source bold and italic resets',any('strong'in r['text']and r['bold']for r in runs)and any('emphasis'in r['text']and r['italic']for r in runs)and any(' then plain.'in r['text']and not r['bold']and not r['italic']for r in runs))
 cells=[]
 for line in(folder/'table-cells.tsv').read_text().splitlines():
  table,row,cell,width,first,merged,firstVertical,vertical=line.split('\t');cells.append(dict(table=int(table),row=int(row),cell=int(cell),width=int(width),firstMerged=first=='true',merged=merged=='true',firstVertical=firstVertical=='true',vertical=vertical=='true'))
 if corpus=='literal':check(file,'literal source did not create tables, pictures or fields',not cells and not pictures and not any(c in raw for c in ['\x13','\x14','\x15']))
 else:
  widths={row:[c for c in cells if c['row']==row]for row in sorted({c['row']for c in cells})};check(file,'HWPF complete source table rows',len(widths)==(3 if corpus=='semantic'else 4)and{c['table']for c in cells}=={0})
  check(file,'HWPF bounded positive source table geometry',all(c['width']>0 for c in cells)and all(len(widths[r])==2 for r in range(3)))
  check(file,'HWPF exact cell and row delimiter counts',fields.count('\x07')==len(cells)+len(widths),dict(actual=fields.count('\x07'),cells=len(cells),rows=len(widths)))
  if corpus=='holdout':
   check(file,'HWPF source row merge first/continuation flags',any(c['row']==1 and c['cell']==0 and c['firstVertical']and c['vertical']for c in cells)and any(c['row']==2 and c['cell']==0 and not c['firstVertical']and c['vertical']for c in cells))
   check(file,'HWPF source wide cell retains two-column width',len(widths[3])==1 and widths[3][0]['width']==sum(c['width']for c in widths[0]))
 check(file,'HWPF original encoded raster bytes',{sha(p.read_bytes())for p in pictures}=={sha((fixtures/p).read_bytes())for p in intent['images']})
 check(file,'Pillow complete original HWPF picture pixels',{pixels(p.read_bytes())for p in pictures}=={pixels((fixtures/p).read_bytes())for p in intent['images']})
 rows.append(dict(file=file.name,sha256=sha(data),bytes=len(data),source=intent['file'],sourceSha256=intent['sha256'],rawParagraphSha256=sha((folder/'paragraphs-raw.txt').read_bytes()),fieldResultSha256=sha((folder/'field-results.txt').read_bytes()),converterTextSha256=sha((folder/'converter-text.txt').read_bytes()),converterAddsUrlAnnotations=compact(converter)!=compact(visible),pictures=[dict(path=p.name,bytes=p.stat().st_size,sha256=sha(p.read_bytes()))for p in pictures],runs=runs,tableCells=cells,bookmarks=bookmarks))
report=dict(checkedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),completeScope=True,files=len(rows),checks=checks,failures=[r for r in checks if not r['passed']],rows=rows,javaProducerSha256=sha(Path('scripts/TextOfficeDocReader.java').read_bytes()),producerSha256=sha(Path(__file__).read_bytes()),readerArtifacts=json.loads(Path('benchmarks/research/text-office1/qa/poi-reader-artifacts.json').read_text()),method='Pinned Apache POI5.4.1 HWPF independently parses actual DOC bytes. getParagraphText raw control data and standard WordExtractor.stripFields display results are both retained. Word cell, soft-break and picture delimiters are typed structures, with exact counts/table rows/merge flags/pictures separately checked. Literal source spacing, all source text/order, original encoded rasters/full pixels and actual character properties are checked. POI getText intentionally annotates URLs and is retained as a separate reader output, never used to alter source intent. No Tabmorph parser/writer or native Office library is imported. Cocoa DOC instruction exposure remains a separate FAILED observation, not normalized away by this independent reader.',standards=['https://poi.apache.org/apidocs/dev/org/apache/poi/hwpf/extractor/WordExtractor.html','https://poi.apache.org/components/document/'],competitiveQuality='No provider output for new pairs; finite independent source-fidelity checks, not broad quality superiority.')
out.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n');print(dict(files=len(rows),checks=len(checks),failures=len(report['failures'])));raise SystemExit(bool(report['failures']))
