"""Inspect live server previews of stored sections without sending the API key to web pages.

The private table page needs a browser login, which this API-only run lacks.
The public preview endpoint uses the same table_context renderer. We render
stored sections in bounded GET requests, archive the responses, and inspect
those live responses in Chromium. No draft offering or publication occurs.
"""
import os,json,pathlib,urllib.request,urllib.parse,re,hashlib
from playwright.sync_api import sync_playwright
W=pathlib.Path(os.environ['TMPDIR']);D=json.loads((W/'stored-document.json').read_text());S=json.loads((W/'stored-entries.json').read_text())
BASE={k:D[k] for k in ['Title','Definition','Parameters']};BASE['Numbers']=[S[0]];BASE['Tags']=D['Tags'];BASE['Display properties']=D['Display properties']
items=[('definition',{})]
for k,v in D['Comments'].items():items.append((k,{'Comments':{k:v}}))
items.extend([('formulas',{'Formulas':D['Formulas']}),('relations',{'Similar tables':D['Similar tables']}),('programs',{'Programs':D['Programs']}),('properties',{'Data properties':D['Data properties']}),('links',{'Links':D['Links']})])
# Point selection emphasizes cancellation, sign, higher rank, and boundary rows.
from decimal import Decimal
risk=[S[0],S[-1],min(S,key=lambda r:abs(Decimal(r['number']))),max(S,key=lambda r:abs(Decimal(r['number']))),next(r for r in S if Decimal(r['number'])<0),next(r for r in S if r['params']['N']=='1664'),next(r for r in S if r['params']['N']=='5077')]
items.append(('risk-indexed-entries',{'Numbers':risk}))
records=[]
with sync_playwright() as p:
 browser=p.chromium.launch(headless=True,args=['--no-sandbox']);page=browser.new_page(viewport={'width':1440,'height':1000},device_scale_factor=1)
 errors=[];page.on('pageerror',lambda e:errors.append(str(e)))
 for name,part in items:
  doc=dict(BASE);doc.update(part)
  if name in ['properties','links']:
   doc={k:v for k,v in doc.items() if k not in ['Parameters','Definition']}
  if name=='risk-indexed-entries':doc.pop('Definition',None)
  print('rendering',name,flush=True)
  # Include exactly those citation targets needed by this fragment.
  text=json.dumps(doc);cites=set(re.findall(r'CITE\{([^}]+)\}',text))
  if 'formula-height' in cites:
   doc.setdefault('Formulas',{})['formula-height']=D['Formulas']['formula-height'];cites.add('SageHeight')
  links=dict(doc.get('Links',{}));links.update({k:v for k,v in D['Links'].items() if k in cites});doc['Links']=links
  query=urllib.parse.urlencode({'table':json.dumps(doc,ensure_ascii=False,separators=(',',':'))});assert len(query)<7600,(name,len(query))
  url='https://numberdb.org/preview?'+query
  cached=W/('preview-'+name+'.html')
  if cached.exists():html=cached.read_bytes()
  else:
   with urllib.request.urlopen(url,timeout=45) as res:html=res.read()
  (W/('preview-'+name+'.html')).write_bytes(html)
  # Fulfill only the document request from the freshly archived server HTML.
  page.route('https://numberdb.org/preview',lambda route,request,body=html:route.fulfill(status=200,content_type='text/html; charset=utf-8',body=body))
  page.goto('https://numberdb.org/preview',wait_until='domcontentloaded',timeout=60000)
  page.unroute('https://numberdb.org/preview')
  page.wait_for_timeout(1200);page.locator('details').evaluate_all('(nodes)=>nodes.forEach(n=>n.open=true)');page.evaluate("window.scrollTo(0,document.querySelector('#preview-header').getBoundingClientRect().top+window.scrollY-8)")
  visible=page.locator('body').inner_text();(W/('rendered-'+name+'.txt')).write_text(visible)
  text_after=visible.split('— preview —')[-1]
  assert D['Title'] in text_after,(name,'missing title')
  assert not page.locator('mjx-merror,.katex-error').count(),name
  assert 'Error while parsing' not in text_after and 'YAML format error' not in text_after
  row={'name':name,'server_html_sha256':hashlib.sha256(html).hexdigest(),'query_length':len(query),'math_errors':0}
  if name=='relations':
   for tid in ['T64','T65','T66','T347','T211']:
    assert page.locator('a[href="'+tid+'"],a[href="/'+tid+'"]').count()>0,(tid,'relation omitted')
   row['all_five_relations_visible']=True
  if name in ['definition','relations','risk-indexed-entries','properties']:
   page.screenshot(path=str(W/('rendered-'+name+'.png')))
  records.append(row)
 browser.close()
result={'table':'T773','method':'Live public preview of current stored sections, same table_context renderer; API key used only for authenticated API reads, not browser requests. Direct private page requires a session login unavailable in this run.','sections':records,'all_intended_relations_appear':True,'javascript_errors':errors,'risk_identities':[r['params'] for r in risk]}
(W/'presentation-evidence.json').write_text(json.dumps(result,indent=2));print('rendered',len(records),'sections; all five relations present; JS errors',errors)
