"""Inspect complete authoritative T770 prose in site-rendered preview slices.
Private page login is unavailable. GET preview has a 4094-byte request-line
limit, so exact source sections are sliced only for transport, without writes.
No credential is sent to Playwright, preview, or external resources.
"""
import os,sys,pathlib,json,urllib.parse,importlib.metadata
sys.path.insert(0,str(pathlib.Path.cwd()))
from numberdb_app.flatten import to_records
from playwright.sync_api import sync_playwright
w=pathlib.Path(os.environ['TMPDIR']);D=json.loads((w/'stored-document.json').read_text());R=to_records(D)
def url(d):return 'https://numberdb.org/preview?'+urllib.parse.urlencode({'table':json.dumps(d,separators=(',',':'),ensure_ascii=False)})
base={'Title':D['Title'],'Numbers':[{'number':R[0]['number']}]}
main={k:D[k] for k in ['Title','Definition','Parameters','Display properties']};main['Numbers']=R[:1]
assert len(url(main))<3950
slices=[main];parts=[]
def chunks(s):
 if len(s)<1100:return [s]
 out=[];start=0;math=False;last=None
 for i,c in enumerate(s):
  if c=='$' and (i==0 or s[i-1]!='\\'):math=not math
  if c.isspace() and not math:last=i+1
  if i-start>=800 and last and last>start:
   out.append(s[start:last]);start=last
 if start<len(s):out.append(s[start:])
 assert ''.join(out)==s
 return out
for k,v in D.items():
 if k in ['Title','Definition','Parameters','Display properties','Numbers']:continue
 if isinstance(v,dict):
  for kk,vv in v.items():
   dd={**base,k:{kk:vv}}
   if len(url(dd))>=3950 and isinstance(vv,str):
    for idx,ch in enumerate(chunks(vv)):parts.append((k,{kk+'-part-'+str(idx):ch}))
   else:parts.append((k,{kk:vv}))
 else:parts.append((k,v))
cur=dict(base)
for k,v in parts:
 trial=json.loads(json.dumps(cur))
 if isinstance(v,dict):trial.setdefault(k,{}).update(v)
 else:trial[k]=v
 if len(url(trial))>=3950:
  slices.append(cur);cur=dict(base)
 if isinstance(v,dict):cur.setdefault(k,{}).update(v)
 else:cur[k]=v
 assert len(url(cur))<3950,(k,len(url(cur)))
slices.append(cur)
for i in [0,192,193,1248]:
 dd={k:D[k] for k in ['Title','Parameters','Display properties']};dd['Numbers']=[R[i]];slices.append(dd)
(w/'preview-plan.json').write_text(json.dumps(slices,ensure_ascii=False,indent=2))
results=[];errors=[]
with sync_playwright() as p:
 browser=p.chromium.launch(headless=True,args=['--no-sandbox']);context=browser.new_context(viewport={'width':1500,'height':1100});page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
 for i,d in enumerate(slices):
  resp=page.goto(url(d),wait_until='networkidle',timeout=60000)
  assert resp.status==200,(i,resp.status)
  page.evaluate('async () => { if (window.MathJax?.startup?.promise) await MathJax.startup.promise; }')
  body=page.locator('body').inner_text()
  dom_text=page.locator('body').text_content();assert D['Title'] in dom_text
  fallback=D['Title'] not in body
  if fallback:
   page.screenshot(path=str(w/f'render-{i:02d}-default.png'),full_page=True)
   page.add_style_tag(content='body,body *:not(mjx-container):not(mjx-container *) {font-family:DejaVu Sans,sans-serif!important;font-size:16px!important;line-height:1.35!important;} pre,code,.CodeMirror * {font-family:DejaVu Sans Mono,monospace!important;}')
   body=page.locator('body').inner_text()
  (w/f'render-{i:02d}-body.txt').write_text(body);assert D['Title'] in body
  merr=page.locator('mjx-merror').all_text_contents();assert not merr,(i,merr)
  if 'Similar tables' in d:
   assert 'scalar entries retain information' in body
   assert page.locator('a[href*="T412"],a[href*="Cyclotomic_p-adic_regulators"]').count()>0
  page.screenshot(path=str(w/f'render-{i:02d}.png'),full_page=True);(w/f'render-{i:02d}.html').write_text(page.content())
  results.append({'slice':i,'status':resp.status,'url_bytes':len(url(d)),'sections':list(d),'math_errors':merr,'diagnostic_font_fallback':fallback,'body_height':page.locator('body').bounding_box()['height'],'screenshot':f'render-{i:02d}.png'})
  print('RENDERED',i+1,len(slices),flush=True)
 versions={'playwright':importlib.metadata.version('playwright'),'chromium':browser.version};browser.close()
(w/'presentation-evidence.json').write_text(json.dumps({'method':__doc__,'private_full_page_login_available':False,'full_source_content_sliced_for_transport':True,'initial_font_limitation':'Resolved for this run by FONTCONFIG_FILE pointing to an artifact configuration of the shared cached fonts. No website or shared runtime changes.', 'fontconfig_file':os.environ.get('FONTCONFIG_FILE'),'slices':results,'page_errors':errors,'versions':versions},indent=2))
assert not errors
print('PRESENTATION_COMPLETE',len(results))
