"""Bundle the original PDF byte streams with a local PDF.js renderer for the sandboxed scene."""
import base64
import json
from pathlib import Path

def attach_reader(html, root):
    root=Path(root)
    assets=root/'scene'/'reader'
    def encode(p):
        return base64.b64encode(p.read_bytes()).decode('ascii')
    docs={}
    for name,title in [('bootstrap','The Spinless Modular Bootstrap at Large Central Charge'),('hawking_page','The Hawking–Page Transition at Weak Coupling')]:
        path='sources/'+name+'.pdf'
        docs[path]={'title':title,'pdf':encode(root/path)}
    for path,title in [('sources.md','Source record'),('claim_ledger.json','Claim ledger')]:
        docs[path]={'title':title,'text':(root/path).read_text()}
    pack={'docs':docs,'library':encode(assets/'pdf.min.mjs'),'worker':encode(assets/'pdf.worker.min.mjs')}
    data=json.dumps(pack,ensure_ascii=True,separators=(',',':')).replace('<',r'\u003c')
    reader=(assets/'paper_reader.html').read_text().replace('__PAPER_PAYLOAD__',data)
    return html.replace('</body>',reader+'\n</body>')
