import os,pathlib,json,urllib.request,urllib.parse,hashlib,mimetypes
from playwright.sync_api import sync_playwright
p=pathlib.Path(os.environ['TMPDIR']);os.environ['TMPDIR']='/home/ubuntu/.cache/numberdb/browser-tmp'
cache=pathlib.Path('/home/ubuntu/.cache/numberdb/render-assets');cache.mkdir(exist_ok=True)
html=(p/'page.html').read_text().replace('<head>','<head><base href="https://numberdb.org/">',1)
requests=[]
def routed(route):
 url=route.request.url;name=hashlib.sha256(url.encode()).hexdigest();f=cache/name;mf=cache/(name+'.json')
 try:
  if f.exists() and mf.exists():data=f.read_bytes();meta=json.load(open(mf))
  else:
   with urllib.request.urlopen(urllib.request.Request(url,headers={'User-Agent':'NumberDB-render-check'}),timeout=25) as a:
    data=a.read();meta={'url':url,'content_type':a.headers.get('Content-Type','application/octet-stream')}
   f.write_bytes(data);mf.write_text(json.dumps(meta))
  route.fulfill(status=200,content_type=meta['content_type'],body=data)
  requests.append({'url':url,'bytes':len(data),'ok':True})
 except Exception as e:
  requests.append({'url':url,'ok':False,'error':type(e).__name__+': '+str(e)});route.abort()
with sync_playwright() as q:
 b=q.chromium.launch(executable_path=q.chromium.executable_path,headless=True,args=['--no-sandbox','--disable-dev-shm-usage','--disable-gpu'])
 page=b.new_page(viewport={'width':1360,'height':1000});errors=[];page.on('pageerror',lambda e:errors.append(str(e)))
 page.goto('data:text/html,<h1>Rendering control</h1>',wait_until='load');assert page.inner_text('body')=='Rendering control'
 page.route('https://**/*',routed);page.set_content(html,wait_until='load',timeout=60000)
 page.wait_for_timeout(2000)
 page.locator('details').evaluate_all('(xs)=>xs.forEach(x=>x.open=true)')
 page.evaluate('async()=>{if(window.MathJax && MathJax.startup && MathJax.startup.promise) await MathJax.startup.promise;}')
 page.screenshot(path=str(p/'rendered-full.png'),full_page=True);page.screenshot(path=str(p/'rendered-top.png'))
 page.evaluate('window.scrollTo(0,document.body.scrollHeight)');page.screenshot(path=str(p/'rendered-bottom.png'))
 text=page.inner_text('body');(p/'rendered-text.txt').write_text(text)
 links=page.locator('a').evaluate_all('(xs)=>xs.map(a=>({text:a.textContent,href:a.getAttribute("href")}))')
 math_nodes=page.locator('mjx-container,.MathJax').count();math_errors=page.locator('.katex-error,.MathJax_Error,mjx-merror,.mjx-merror').count()
 assert 'Similar tables' in text and all(s in text for s in ['CM coefficients of the mirror quartic','Period map of the Dwork','Minimal polynomials of monstrous','Hilbert class polynomials','Canonical modular polynomials'])
 assert all(s not in text for s in ['CITE{','HREF{','Unknown key'])
 result={'page_errors':errors,'math_errors':math_errors,'rendered_math_nodes':math_nodes,'links':links,'asset_requests':requests,'snapshot':'page.html','body_characters':len(text),'all_five_relations_visible':True,'method':'Exact authenticated server HTML; original assets fetched through urllib and cached by URL; shared full Chromium with cached fonts; browser receives no credentials'}
 (p/'render-results.json').write_text(json.dumps(result,indent=2))
 print('Body length',len(text),'math nodes',math_nodes,'math errors',math_errors,'page errors',errors,flush=True)
 b.close()
assert math_nodes>20 and not math_errors and not errors
