"""Render all stored sections using NumberDB previews, then inspect a composite.
The live private table requires a session login unavailable in this API-only
run. This artifact is explicitly a composition of exact server-rendered
sections, not evidence that an authenticated direct table page was visited.
"""
import os,json,re,urllib.request,urllib.parse,hashlib,base64
from pathlib import Path
from bs4 import BeautifulSoup
from playwright.sync_api import sync_playwright
w=Path(os.environ['TMPDIR']);D=json.loads((w/'readback-document.json').read_text())
def load(name):return BeautifulSoup((w/('preview-'+name+'.html')).read_text(),'html.parser')
def section(name,title):
 soup=load(name)
 heading=next(x for x in soup.select('div.table-section-title') if x.get_text(' ',strip=True)==title)
 container=heading.find_next_sibling('div',class_='table-section-container')
 assert container is not None,(name,title)
 return heading,container
base=load('numbers-N1')
for form in base.select('form'):form.decompose()
for script in list(base.select('script')):
 if 'CodeMirror.fromTextArea' in script.get_text():script.decompose()
# Retain the full original preview styling and rendering of the title/numbers.
numberbox=base.select_one('div.table-number-section-container')
for N in list(D['Numbers'])[1:]:
 source=load('numbers-N'+N).select_one('div.table-number-section-container')
 for child in list(source.contents):numberbox.append(child.extract())
# Remove the base Parameters block; insert the complete prose in natural order.
for heading in list(base.select('div.table-section-title')):
 if heading.get_text(' ',strip=True)!='Numbers':
  nxt=heading.find_next_sibling('div',class_='table-section-container')
  if nxt:nxt.decompose()
  heading.decompose()
anchor=base.select_one('div.table-number-section-outer-container')
for title,names in [('Definition',['definition']),('Parameters',['parameters']),
 ('Comments',['comments-'+str(i) for i in range(len(D['Comments']))]),
 ('Formulas',['formulas-'+str(i) for i in range(len(D['Formulas']))]),
 ('Similar tables',['similar']),('Links',['bibliography']),('References',['bibliography']),
 ('Programs',['programs']),('Data properties',['properties','rigour'])]:
 first=True
 for name in names:
  heading,container=section(name,title)
  if first:anchor.insert_after(heading);anchor=heading;first=False
  anchor.insert_after(container);anchor=container
out=w/'rendered-composite.html';out.write_text(str(base))
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)))
 page.route('https://numberdb.org/preview',lambda route:route.fulfill(status=200,content_type='text/html',body=out.read_text()))
 page.goto('https://numberdb.org/preview',wait_until='networkidle',timeout=60000)
 page.evaluate('''async b64=>{const bytes=Uint8Array.from(atob(b64), c=>c.charCodeAt(0));const font=new FontFace('Source Sans Pro',bytes.buffer,{weight:'400',style:'normal'});await font.load();document.fonts.add(font);await document.fonts.ready;}''',base64.b64encode((w/'sourcesanspro-400.woff2').read_bytes()).decode())
 page.evaluate("""async b64=>{const bytes=Uint8Array.from(atob(b64), c=>c.charCodeAt(0));const font=new FontFace('NumberDB Mono',bytes.buffer,{weight:'400',style:'normal'});await font.load();document.fonts.add(font);await document.fonts.ready;}""",base64.b64encode((w/'source-code-pro-400.woff2').read_bytes()).decode())
 page.add_style_tag(content="pre,code{font-family:'NumberDB Mono',monospace;}")
 page.evaluate("document.querySelectorAll('details').forEach(e=>e.open=true)")
 page.wait_for_timeout(1000)
 diagnostics=page.evaluate('''()=>({bodyStyle:getComputedStyle(document.body).cssText, title:getComputedStyle(document.querySelector('#table-title')).visibility, titleDisplay:getComputedStyle(document.querySelector('#table-title')).display,bodyText:document.body.textContent.slice(0,300),titleText:document.querySelector('#table-title').textContent,bodyHTML:document.body.innerHTML.slice(0,100)})''')
 print('DIAGNOSTICS',json.dumps(diagnostics),errors,flush=True)
 page.screenshot(path=str(w/'render-before-check.png'),full_page=True)
 body=page.locator('body').inner_text();(w/'rendered-text.txt').write_text(body)
 count=page.locator('div.table-number').count();assert count==18,count
 section_titles=page.locator('div.table-section-title').all_text_contents()
 assert all(t in section_titles for t in ('Numbers','Definition','Parameters','Comments','Formulas','Similar tables','Links','References','Programs','Data properties'))
 assert 'signed real primitive odd period' in body and '100 significant digits' in body
 assert 'HREF{' not in body and 'CITE{' not in body
 assert 'real(polcoef(P,9))/4' in body
 assert page.locator('code.table-code').evaluate('(el)=>el.getBoundingClientRect().height')>20
 similar=page.locator('div.table-section-title').filter(has_text='Similar tables').locator('xpath=following-sibling::div[1]')
 hrefs=similar.locator('a.HREF').evaluate_all('(nodes)=>nodes.map(n=>n.getAttribute("href"))')
 assert set(hrefs)=={'T696','T765','T323','T683','T326','T684'},hrefs
 math_errors=page.locator('.MathJax_Error,mjx-merror').count()
 assert math_errors==0
 page.locator('div.table-number-section-container').evaluate_all('nodes=>nodes.forEach(el=>{el.style.maxHeight="none";el.style.height="auto";el.style.overflow="visible";})')
 page.screenshot(path=str(w/'rendered-full.png'),full_page=True)
 page.locator('div.table-number-section-outer-container').screenshot(path=str(w/'rendered-numbers.png'))
 similar.screenshot(path=str(w/'rendered-similar.png'))
 screenshot_hashes={n:hashlib.sha256((w/n).read_bytes()).hexdigest() for n in ('rendered-full.png','rendered-numbers.png','rendered-similar.png')}
 result={'table':'T766','method':'Composition of all original stored content from successful NumberDB server-rendered preview sections; browser inspection of the complete composition.',
 'direct_private_page_inspected':False,'direct_private_page_http_status':404,'full_numbers_single_request_preview_status':400,
 'reason':'API key permits authenticated API reads; a website browser session is unavailable. The combined-number preview request returned HTTP 400; per-level previews succeeded. No token was sent to a non-API route.',
 'screenshot_note':'The local composition expands the number scroll box and rigour note so all rows and paragraphs are visible. Comments/formulas retain per-preview numbering; citations use the full original bibliography and correct targets.',
 'number_cells':count,'intended_similar_relations':6,'rendered_similar_hrefs':hrefs,'section_titles':section_titles,
 'font_environment_note':'This runtime has no installed system fonts. Public Source Sans Pro and Source Code Pro fonts were loaded explicitly, with a local monospace fallback for code; browser-fonts.json records sources and hashes. The website was not changed.',
 'math_render_errors':math_errors,'browser_page_errors':errors,'screenshots':screenshot_hashes,
 'limitations':'The independent critic/controller should inspect the direct draft page with an authorized browser session. This composition is not a substitute assertion of direct-page access.'}
 (w/'presentation-evidence.json').write_text(json.dumps(result,indent=2));print(json.dumps(result))
 browser.close()
