"""Check the live preview renderer using exact sections of the read-back draft.
The private T-number page requires a login session which this run lacks.
No token is passed to a browser or embedded in a preview URL.
"""
import os,json,pathlib,urllib.parse,urllib.request,hashlib,sys,base64
sys.path.insert(0,os.getcwd())
from numberdb_app.flatten import to_records
from playwright.sync_api import sync_playwright
w=pathlib.Path(os.environ['TMPDIR']);font=pathlib.Path('/home/ubuntu/.cache/numberdb/inspection-font.woff2').read_bytes();font_url='https://numberdb.org/static/numberdb-inspection-font.woff2';doc=json.loads((w/'stored-document.json').read_text())
doc['Numbers']=to_records(doc)
results={'table':'T752','direct_page':None,'preview_sections':[],'limitations':['No browser login session is supplied. Full live preview exceeds the server URI limit, so exact read-back document sections are rendered separately.']}
try:
 with urllib.request.urlopen('https://numberdb.org/T752',timeout=30) as r:results['direct_page']=r.status
except urllib.error.HTTPError as e:results['direct_page']=e.code
base={'Title':doc['Title'],'Parameters':doc['Parameters'],'Display properties':doc['Display properties']}
# Every original section is rendered. The Numbers section is split into 15-row pages.
sections=[['Definition','Comments','Tags'],['Formulas','Similar tables'],['References','Links','Programs','Keywords'],['Data properties']]
cases=[]
for i,names in enumerate(sections):
 d={**base,**{n:doc[n] for n in names},'Numbers':doc['Numbers'][:3]}
 if any(n in names for n in ['Definition','Comments','Formulas']): d['References']=doc['References']
 if 'Data properties' in names: d['Links']={'FLINT':doc['Links']['FLINT']}
 cases.append((f'prose-{i+1}',d,names))
for i in range(0,len(doc['Numbers']),15):
 d={**base,'Numbers':doc['Numbers'][i:i+15]};cases.append((f'entries-{i//15+1}',d,['Numbers']))
with sync_playwright() as p:
 browser=p.chromium.launch(headless=True,args=['--no-sandbox','--disable-dev-shm-usage'])
 page=browser.new_page(viewport={'width':1440,'height':1050})
 page.on('console',lambda msg: print('BROWSER_CONSOLE',msg.type,msg.text[:350],flush=True))
 for label,d,names in cases:
  url='https://numberdb.org/preview?'+urllib.parse.urlencode({'table':json.dumps(d,ensure_ascii=False,separators=(',',':'))})
  response=page.goto(url,wait_until='networkidle',timeout=60000)
  assert response.status==200,(label,response.status)
  page.evaluate("""async (bytes) => {const f = new FontFace('NumberDBInspection', new Uint8Array(bytes).buffer); await f.load();document.fonts.add(f);} """, list(font))
  page.add_style_tag(content="body,body * {font-family:'NumberDBInspection' !important;} .CodeMirror {height:160px !important;}")
  page.wait_for_timeout(500)
  html=page.content();(w/('rendered-final-'+label+'.html')).write_text(html)
  page.screenshot(path=str(w/('rendered-final-'+label+'.png')),full_page=True)
  text=page.inner_text('body');errors=page.locator('.katex-error,merror,.MathJax_Error').all_text_contents()
  r={'case':label,'sections':names,'status':response.status,'url_length':len(url),'math_errors':errors,'inspection_font':'shared inspection-font.woff2; CSS family override for missing host fonts','body_characters':len(text),'screenshot':'rendered-final-'+label+'.png'}
  if 'Similar tables' in names:
   paths={urllib.parse.urlparse(a).path.rstrip('/') for a in page.locator('a[href]').evaluate_all('(nodes) => nodes.map(n=>n.href)')}
   r['companion_links']={tid:('/'+tid) in paths for tid in ['T15','T733','T3','T36','T31']}
   assert all(r['companion_links'].values()),r
  assert not errors,r
  assert len(text)>500,r
  results['preview_sections'].append(r);print('RENDER',json.dumps(r),flush=True)
 browser.close()
(w/'browser-results.json').write_text(json.dumps(results,indent=2)+'\n')
