"""Render the canonical papers to accessible HTML, plain Markdown and PDFs."""
import pathlib, re, html, json, shutil, csv, os
from manuscripts import PAPERS,ROOT
from reportlab.platypus import SimpleDocTemplate,Paragraph,Spacer,Image,Table,TableStyle,KeepTogether
from reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.enums import TA_LEFT
out=ROOT/'release';out.mkdir(exist_ok=True);(ROOT/'output/pdf').mkdir(parents=True,exist_ok=True)
fontroot=pathlib.Path.home()/'.cache/codex-runtimes/codex-primary-runtime/dependencies/native/libreoffice-headless/libreoffice/LibreOfficeDev.app/Contents/Resources/fonts/truetype'
fontroot=pathlib.Path(os.environ.get('AUSTRALIS_FONT_DIR',str(fontroot)))
if not fontroot.exists():fontroot=pathlib.Path('/usr/share/fonts/truetype/dejavu')
pdfmetrics.registerFont(TTFont('Body',str(fontroot/'DejaVuSans.ttf')))
pdfmetrics.registerFont(TTFont('BodyBold',str(fontroot/'DejaVuSans-Bold.ttf')))
pdfmetrics.registerFontFamily('Body',normal='Body',bold='BodyBold')
style=getSampleStyleSheet()
style.add(ParagraphStyle(name='BodyTextCustom',fontName='Body',fontSize=9.1,leading=14,spaceAfter=9,textColor=colors.HexColor('#263A42')))
style.add(ParagraphStyle(name='TitleCustom',fontName='BodyBold',fontSize=21,leading=27,spaceAfter=15,textColor=colors.HexColor('#073F45')))
style.add(ParagraphStyle(name='HeadingCustom',fontName='BodyBold',fontSize=12,leading=17,spaceBefore=12,spaceAfter=6,textColor=colors.HexColor('#006C70'),keepWithNext=True))
style.add(ParagraphStyle(name='SmallCustom',fontName='Body',fontSize=7.5,leading=11,spaceAfter=8,textColor=colors.HexColor('#50636B')))
style.add(ParagraphStyle(name='CellCustom',fontName='Body',fontSize=7.2,leading=10,spaceAfter=0))
css='''*{box-sizing:border-box}body{margin:0;background:#f5f7f6;color:#203b41;font:18px/1.7 Georgia,serif}main{max-width:920px;margin:40px auto;background:white;padding:50px 64px;border-top:6px solid #006c70}header .brand{font:700 12px/1.5 Arial,sans-serif;letter-spacing:.14em;color:#006c70}h1{font:700 38px/1.18 Georgia,serif;color:#073f45;margin:18px 0}h2{font:700 24px/1.3 Arial,sans-serif;margin-top:38px;color:#006c70}.status{background:#eff5f4;border-left:4px solid #b15428;padding:12px 16px;font:14px/1.6 Arial,sans-serif}.subtitle{font-size:21px;color:#50636b}a{color:#006c70;text-underline-offset:3px;overflow-wrap:anywhere}figure{margin:30px 0}img{width:100%;height:auto}figcaption,.caption,.reference{font:14px/1.65 Arial,sans-serif;color:#40575e}.table-wrap{overflow-x:auto}table{border-collapse:collapse;width:100%;font:14px/1.6 Arial,sans-serif}th,td{text-align:left;padding:10px;border-bottom:1px solid #d5e1df}th{background:#eaf1ef}nav{font:14px/1.7 Arial,sans-serif;padding:12px 0}footer{border-top:1px solid #d5e1df;margin-top:32px;padding-top:16px;font:13px/1.65 Arial,sans-serif}@media(max-width:650px){body{font-size:17px}main{margin:0;padding:25px 20px}h1{font-size:30px}h2{font-size:22px}}@media print{body{background:white}main{margin:0;border:0;padding:0}nav{display:none}}'''
(out/'research.css').write_text(css)
def escaped(s):return html.escape(s)
def links(s):
 s=escaped(s)
 return re.sub(r'https://[^\s<]+',lambda m:f'<a href="{m[0]}">{m[0]}</a>',s)
def pdftext(s):
 for ch in ['−','–','—','‑']:s=s.replace(ch,'-')
 return links(s)
def footer(canvas,doc):
 canvas.saveState();canvas.setStrokeColor(colors.HexColor('#D5E1DF'));canvas.line(46,43,549,43)
 canvas.setFont('Body',7);canvas.setFillColor(colors.HexColor('#50636B'));canvas.drawString(46,29,'Australis Biogenetics | Unreviewed AI-assisted computational research')
 canvas.drawRightString(549,29,str(doc.page));canvas.restoreState()
for p in PAPERS:
 (ROOT/'papers'/f"{p['id']}.json").write_text(json.dumps(p,ensure_ascii=False,indent=2)+'\n')
 head=f'<header><p class="brand">AUSTRALIS BIOGENETICS · RESEARCH NOTES</p><h1>{escaped(p["title"])}</h1><p class="subtitle">{escaped(p["subtitle"])}</p><p class="status">{escaped(p["status"])}<br>Secondary analyses of public data. No human scientific signoff or peer review is asserted.</p></header>'
 nav=f'<nav aria-label="Downloads"><a href="{p["id"]}.pdf">Download PDF</a> · <a href="australis-research-reproduction.zip">Download data and code</a> · <a href="index.html">Research index</a></nav>'
 elems=[];story=[Paragraph('AUSTRALIS BIOGENETICS / RESEARCH NOTES',style['SmallCustom']),Paragraph(pdftext(p['title']),style['TitleCustom']),Paragraph(pdftext(p['subtitle']),style['BodyTextCustom']),Paragraph(pdftext(p['status']),style['SmallCustom'])];md=[f'# {p["title"]}',p['subtitle'],p['status']];refnum=0
 for b in p['blocks']:
  t=b['type']
  if t=='h2':elems.append(f'<h2>{escaped(b["text"])}</h2>');story.append(Paragraph(pdftext(b['text']),style['HeadingCustom']));md.append('## '+b['text'])
  elif t in ['p','ref']:
   s=b['text']
   if t=='ref':refnum+=1;s=f'[{refnum}] '+s
   elems.append(f'<p class="{"reference" if t=="ref" else "body"}">{links(s)}</p>');story.append(Paragraph(pdftext(s),style['SmallCustom' if t=='ref' else 'BodyTextCustom']));md.append(s)
  elif t=='figure':
   shutil.copy2(ROOT/'results'/b['path'],out/b['path']);shutil.copy2(ROOT/'results'/b['path'].replace('.png','.svg'),out/b['path'].replace('.png','.svg'))
   elems.append(f'<figure><img src="{b["path"]}" alt="{escaped(b["alt"])}" loading="lazy"><figcaption>{escaped(b["caption"])}</figcaption></figure>')
   story.append(KeepTogether([Image(str(ROOT/'results'/b['path']),width=495,height=309.375),Paragraph(pdftext(b['caption']),style['SmallCustom'])]));md.extend([f'![{b["alt"]}]({b["path"]})',b['caption']])
  elif t=='table':
   elems.append('<div class="table-wrap"><table><caption class="caption">'+escaped(b['caption'])+'</caption><thead><tr>'+''.join('<th scope="col">'+escaped(x)+'</th>' for x in b['headers'])+'</tr></thead><tbody>'+''.join('<tr>'+''.join('<td>'+escaped(x)+'</td>' for x in row)+'</tr>' for row in b['rows'])+'</tbody></table></div>')
   cells=[[Paragraph(pdftext(x),style['CellCustom']) for x in row] for row in [b['headers']]+b['rows']]
   widths=[180,65,250] if len(b['headers'])==3 else [100,75,250,70]
   tab=Table(cells,colWidths=widths,repeatRows=1,hAlign='LEFT');tab.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),colors.HexColor('#EAF1EF')),('VALIGN',(0,0),(-1,-1),'TOP'),('LINEBELOW',(0,0),(-1,-1),.3,colors.HexColor('#D5E1DF')),('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7)]));story.extend([Paragraph(pdftext(b['caption']),style['SmallCustom']),tab,Spacer(1,10)])
   md.extend([b['caption'],'| '+' | '.join(b['headers'])+' |','| '+' | '.join('---' for x in b['headers'])+' |']+['| '+' | '.join(row)+' |' for row in b['rows']])
 htmlbody=head+nav+'\n'.join(elems)+'<footer>Data attribution: Human Ageing Genomic Resources, CC BY 3.0. Reproduction and source-audit details are included in the downloadable archive.</footer>'
 (out/f"{p['id']}.html").write_text('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>'+escaped(p['title'])+'</title><link rel="stylesheet" href="research.css"></head><body><main>'+htmlbody+'</main></body></html>')
 (out/f"{p['id']}-wordpress.html").write_text('<article class="australis-research-paper">'+htmlbody+'</article>')
 (ROOT/'papers'/f"{p['id']}.md").write_text('\n\n'.join(md)+'\n')
 pdfpath=ROOT/'output/pdf'/f"{p['id']}.pdf"
 SimpleDocTemplate(str(pdfpath),pagesize=(595.28,841.89),rightMargin=50,leftMargin=46,topMargin=44,bottomMargin=60,title=p['title'],author='AI-assisted analysis prepared for Australis Biogenetics',subject='Unreviewed computational research; no human signoff asserted').build(story,onFirstPage=footer,onLaterPages=footer)
 shutil.copy2(pdfpath,out/pdfpath.name)
(out/'index.html').write_text('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Australis Biogenetics research notes</title><link rel="stylesheet" href="research.css"></head><body><main><header><p class="brand">AUSTRALIS BIOGENETICS</p><h1>Reproducible longevity research</h1><p class="status">Two unreviewed AI-assisted computational studies. These analyses do not establish treatments or human life extension.</p></header>'+''.join(f'<section><h2><a href="{p["id"]}.html">{escaped(p["short_title"])}</a></h2><p>{escaped(p["subtitle"])}</p></section>' for p in PAPERS)+'<p><a href="australis-research-reproduction.zip">Download all data, code, protocols and results</a></p></main></body></html>')
print('Rendered two manuscripts to HTML, Markdown and PDF.')
