"""Render authenticated live HTML with public assets and no browser credentials.

fetch_presentation.py captures the authorized HTML separately. Browser
requests replay only those responses and fetch public assets normally.
"""
import os,json,pathlib,re,hashlib,importlib.metadata
from playwright.sync_api import sync_playwright
w=pathlib.Path(os.environ['TMPDIR']);doc=json.loads((w/'stored-document.json').read_text())
results={'table':'T716','pages':[],'console_errors':[],'method':'Live authenticated HTML replayed at its original URL; browser has no credentials'}
with sync_playwright() as p:
 browser=p.chromium.launch(headless=True,args=['--no-sandbox','--disable-dev-shm-usage','--disable-gpu'])
 context=browser.new_context(viewport={'width':1440,'height':1000})
 page=context.new_page();page.on('pageerror',lambda e:results['console_errors'].append(str(e)))
 for name,url in [('table','https://numberdb.org/T716'),('history','https://numberdb.org/history/T716')]:
  source=w/(name+'-page.html')
  page.route(url,lambda route,request,source=source:route.fulfill(status=200,content_type='text/html',body=source.read_text()))
  response=page.goto(url,wait_until='domcontentloaded',timeout=60000)
  if name=='table':
   page.wait_for_function('typeof MathJax !== "undefined" && !!MathJax.typesetPromise',timeout=30000)
   page.evaluate('MathJax.typesetPromise()')
   page.locator('details.prose-more').evaluate_all('(els)=>els.forEach(e=>e.open=true)')
  body=page.locator('body').inner_text();(w/(name+'-rendered.txt')).write_text(body)
  page.screenshot(path=str(w/(name+'-rendered.png')),full_page=True)
  page.screenshot(path=str(w/(name+'-top.png')))
  (w/(name+'-rendered.html')).write_text(page.content())
  results['pages'].append({'name':name,'status':response.status,'url':page.url,'title':page.title(),'math_errors':page.locator('mjx-merror,[data-mml-node=merror],.katex-error').all_text_contents(),'raw_HREF':'HREF{' in body,'raw_CITE':'CITE{' in body,'has_table_title':'Harmonic central binomial sums' in body,'body_characters':len(body),'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest()})
  if name=='table':
   nums=[r['number'] for r in json.loads((w/'stored-rows.json').read_text())['rows']]
   results['decimal_count']=sum(s in body for s in nums)
   links=page.locator('a').evaluate_all('(els)=>els.map(a=>({text:a.innerText,href:a.href}))')
   (w/'rendered-links.json').write_text(json.dumps(links,indent=2))
   def texts(x):
    if isinstance(x,str):yield x
    elif isinstance(x,dict):
     for v in x.values():yield from texts(v)
    elif isinstance(x,list):
     for v in x:yield from texts(v)
   formulas=[f for t in texts(doc) for f in re.findall(r'\$([^$]+)\$',t)]
   results['all_math']=page.evaluate('''async fs => {let errors=[];for(const f of fs){try{let n=await MathJax.tex2svgPromise(f);if(n.querySelector('mjx-merror,[data-mml-node=merror]'))errors.push(f);}catch(e){errors.push(f);}}return {count:fs.length,errors};}''',formulas)
   results['invalid_tex_rejected']=page.evaluate('''async () => {let n=await MathJax.tex2svgPromise('\\\\frac{1}{');return !!n.querySelector('mjx-merror,[data-mml-node=merror]');}''')
   for title in ['Definition','Formulas','Data properties','References']:
    loc=page.get_by_text(title,exact=True)
    if loc.count()==1:
     loc.scroll_into_view_if_needed();page.screenshot(path=str(w/('table-'+title.lower().replace(' ','-')+'.png')))
 results['playwright']=importlib.metadata.version('playwright');results['chromium']=browser.version
 context.close();browser.close()
(w/'browser-results.json').write_text(json.dumps(results,indent=2));print(json.dumps(results))
assert results['decimal_count']==32 and not results['console_errors']
assert not results['all_math']['errors'] and results['invalid_tex_rejected']
assert all(not r['math_errors'] and not r['raw_HREF'] and not r['raw_CITE'] for r in results['pages'])
