"""Credential-free live previews, assembled only from returned server HTML.

The public preview's GET URL cannot carry the full 84-row source (HTTP 414).
Each part uses exact stored fields and the same site's renderer; the full local
page contains every rendered part and all 84 rows. It is not an authenticated
view of the private draft's page chrome. This limitation is recorded in handoff.
"""
import os,json,urllib.request,urllib.parse,copy,hashlib
from pathlib import Path
import yaml
from bs4 import BeautifulSoup
w=Path(os.environ['TMPDIR']);root=w/'render';root.mkdir(exist_ok=True)
d=json.loads((w/'stored.json').read_text());support={k:d[k] for k in ('Title','References','Links','Parameters','Display properties')};support['Data properties']={'type':'R'}
parts=[]
for field in ['Definition','Parameters','Comments','Formulas','Keywords','Tags','Similar tables','Links','References','Programs','Data properties']:
 payload=copy.deepcopy(support);payload[field]=d[field];parts.append((field,payload))
items=list(d['Numbers'].items())
for i in range(0,len(items),12):
 payload={k:d[k] for k in ('Title','Parameters','Display properties')};payload['Data properties']={'type':'R'};payload['Numbers']=dict(items[i:i+12]);parts.append(('Numbers-'+str(i),payload))
records=[];sections={};number_containers=[];template=None;header=None
for label,payload in parts:
 y=yaml.safe_dump(payload,sort_keys=False,allow_unicode=True);url='https://numberdb.org/preview?'+urllib.parse.urlencode({'table':y});assert len(url)<8000,(label,len(url))
 b=urllib.request.urlopen(url,timeout=60).read();name=label.replace(' ','-')+'.html';(root/name).write_bytes(b)
 soup=BeautifulSoup(b,'html.parser')
 if template is None:template=soup;header=copy.copy(soup.select_one('#table-title'))
 titles=soup.select('.table-section-title');heads=[x.get_text(' ',strip=True) for x in titles]
 print(label,'URL length',len(url),'headings',heads,flush=True)
 if label.startswith('Numbers-'):
  container=soup.select_one('.table-number-section-outer-container');assert container;number_containers.append(container)
 else:
  matches=[x for x in titles if x.get_text(' ',strip=True).lower()==label.lower()]
  if not matches and label=='Tags':
   # Tags are rendered in the title/header rather than a separate section.
   pass
  elif not matches and label=='Keywords':pass
  else:
   assert len(matches)==1,(label,heads)
   h=matches[0];sections[label]=str(h)+str(h.find_next_sibling())
 records.append({'field':label,'file':name,'source_sha256':hashlib.sha256(y.encode()).hexdigest(),'html_sha256':hashlib.sha256(b).hexdigest(),'headings':heads})
# Use the real live preview's head/resources, replacing its body with all actual
# server-rendered sections and complete entry blocks. No prose/math is re-rendered locally.
styles=[copy.copy(x) for x in template.find_all('style')]
for style in styles: template.head.append(style)
body=template.body;body.clear();body.append(header)
for label in ['Definition','Parameters','Comments','Formulas','Similar tables','Links','References','Programs','Data properties']:
 body.append(BeautifulSoup(sections[label],'html.parser'))
for i,container in enumerate(number_containers):
 if i:container.select_one('.table-section-title').decompose()
 body.append(copy.copy(container))
# Preserve the actual header's tag list from the Tags preview.
tag_soup=BeautifulSoup((root/'Tags.html').read_bytes(),'html.parser')
for n in tag_soup.select('a[href^="/tags/"]'):
 body.insert(1,copy.copy(n))
base=template.new_tag('base',href='https://numberdb.org/');template.head.insert(0,base)
(w/'rendered-complete.html').write_text(str(template));(root/'manifest.json').write_text(json.dumps(records,indent=2))
print('assembled all sections and',len(items),'entries')
