"""Independent HTML/CommonMark, ZIP/XML and Pillow reads of actual UI downloads."""
from pathlib import Path
import sys, json, hashlib, io, zipfile, base64, xml.etree.ElementTree as ET
sys.path.insert(0, str(Path('benchmarks/research/word-text-breaks/qa-reader/commonmark-0.9.1.whl').resolve()))
import commonmark
from bs4 import BeautifulSoup
from PIL import Image

folder=Path(sys.argv[1]);report=Path(sys.argv[2]);manifest=json.loads(Path('benchmarks/fixtures/rtf-content1/manifest.json').read_text());capture=json.loads((folder/'capture.json').read_text());checks=[];observations=[]
def check(name, actual, expected):
 checks.append({'check':name,'actual':actual,'expected':expected,'pass':actual==expected})
def digest(b):return hashlib.sha256(b).hexdigest()
def soup(text):return BeautifulSoup(text,'html.parser')
def inspect_html(text, case, name, markdown=False):
 doc=soup(commonmark.commonmark(text)if markdown else text);body=doc.body or doc;value=body.get_text()
 for absent in case['omitted']:check(name+': omit '+absent,absent in value,False)
 if case['id']=='breaks':
  check(name+': Unicode alternative', 'ALT_START 世界 ALT_END' in value,True)
  check(name+': literal markup', 'X_START <tag> &copy; **literal** [square] X_END' in value,True)
  check(name+': source soft line break',len(body.find_all('br')),1)
  if not markdown:check(name+': source paragraphs including empty',len(body.find_all('p',recursive=False)),7)
  observations.append({'output':name,'paragraphs':len(body.find_all('p',recursive=False)),'emptyParagraphs':sum(not p.get_text()and not p.find('img')for p in body.find_all('p',recursive=False)),'markdownEmptyParagraphLimit':markdown})
 else:
  positions=[value.find(marker)for marker in case['requiredInOrder']];check(name+': all source marker order',all(p>=0 for p in positions)and positions==sorted(positions),True)
  check(name+': heading', [h.get_text()for h in body.find_all('h1')],['CONTENT_HEADING'])
  check(name+': bold', [e.get_text()for e in body.find_all(['strong','b'])],['bold text'])
  check(name+': italic',[e.get_text()for e in body.find_all(['em','i'])],['italic text'])
  check(name+': underline',[e.get_text()for e in body.find_all('u')],['underlined text'])
  check(name+': table cells',[[td.get_text()for td in tr.find_all(['td','th'],recursive=False)]for tr in body.find('table').find_all('tr')],case['cells'])
  check(name+': ordinary hyperlink',any(a.get('href')==case['link']and a.get_text()=='Useful link'for a in body.find_all('a')),True)
  imgs=body.find_all('img');check(name+': image count',len(imgs),1)
  if imgs:
   raw=base64.b64decode(imgs[0]['src'].split(',',1)[1]);im=Image.open(io.BytesIO(raw)).convert('RGBA');check(name+': whole source image dimensions',list(im.size),[case['image']['width'],case['image']['height']]);check(name+': whole decoded source RGBA',digest(im.tobytes()),case['image']['rgbaSha256'])
  observations.append({'output':name,'footnotePresent':'FOOTNOTE_BODY'in value,'bodyText':value})
 if not markdown:check(name+': inert exported HTML',len(body.find_all(['script','iframe','object','embed','style','link'])),0)

check('UI complete',capture['complete'],True);check('actual download count',len(capture['rows']),16)
for row in capture['rows']:
 if not row.get('output'):check('UI '+row['browser']+' completed',row.get('pass'),True);continue
 name=row['output'];data=(folder/name).read_bytes();case=next(c for c in manifest['cases']if c['source']==row['source'])
 check(name+': original input hash',digest(Path(case['source']).read_bytes()),row['inputSha256']);check(name+': downloaded hash',digest(data),row['sha256'])
 if row['to']=='txt':
  text=data.decode('utf-8')
  if case['id']=='breaks':check(name+': exact declared body text and whitespace',text,case['expectedTxt'])
  for absent in case['omitted']:check(name+': omit '+absent,absent in text,False)
  if case['id']=='rich':
   positions=[text.find(marker)for marker in case['requiredInOrder']];check(name+': all source marker order',all(p>=0 for p in positions)and positions==sorted(positions),True)
 elif row['to']in ['html','md']:inspect_html(data.decode('utf-8'),case,name,row['to']=='md')
 else:
  with zipfile.ZipFile(io.BytesIO(data))as z:
   W='{http://schemas.openxmlformats.org/wordprocessingml/2006/main}';doc=ET.fromstring(z.read('word/document.xml'));body=doc.find(W+'body')
   if case['id']=='breaks':
    paragraphs=[''.join((e.text or'')if e.tag==W+'t'else'\n'if e.tag==W+'br'else'\t'if e.tag==W+'tab'else''for e in p.iter())for p in body.findall(W+'p')];check(name+': independent native source paragraphs',paragraphs,case['bodyParagraphs'])
   else:
    check(name+': native explicit underline',len(doc.findall('.//'+W+'u'))>=1,True)
    imageNames=[n for n in z.namelist()if n.startswith('word/media/')];check(name+': native image count',len(imageNames),1)
    if imageNames:
     im=Image.open(io.BytesIO(z.read(imageNames[0]))).convert('RGBA');check(name+': native complete RGBA',digest(im.tobytes()),case['image']['rgbaSha256'])
result={'reader':'BeautifulSoup HTML parser; CommonMark 0.9.1 independent Markdown renderer; Python ZIP/ElementTree; native Pillow','outputs':sum('output'in r for r in capture['rows']),'checks':checks,'observations':observations,'failures':[c for c in checks if not c['pass']],'scope':'Two original RTF corpora; DOCX controls are derivatives. Complete original source/decoded-image data remain unchanged. Markdown intentionally collapses an empty paragraph and a tab to flow whitespace; this is not printed-layout fidelity.'}
report.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print(json.dumps({'outputs':result['outputs'],'checks':len(checks),'failures':len(result['failures'])}));sys.exit(bool(result['failures']))
