import zipfile, pathlib, subprocess, json, datetime, sys
root = pathlib.Path(__file__).parent
out = root / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
out.mkdir()
for ext in ['xhtml', 'xht']:
    with zipfile.ZipFile(out / f'chapters-{ext}.epub', 'w') as z:
        z.writestr('mimetype', 'application/epub+zip')
        z.writestr('META-INF/container.xml', '<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OEBPS/book.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
        z.writestr('OEBPS/book.opf', f'''<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">ferry</dc:identifier><dc:title>Ferry</dc:title><dc:language>en</dc:language></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="dawn" href="dawn.{ext}" media-type="application/xhtml+xml"/><item id="dusk" href="dusk.{ext}" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="dawn"/><itemref idref="dusk"/></spine></package>''')
        z.writestr('OEBPS/nav.xhtml', f'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><body><nav epub:type="toc"><ol><li><a href="dawn.{ext}">Dawn</a></li><li><a href="dusk.{ext}">Dusk</a></li></ol></nav></body></html>')
        for name, title, text in [('dawn','Dawn','Take the 07:15 ferry.'), ('dusk','Dusk','Meet at Pier 8.')]:
            z.writestr(f'OEBPS/{name}.{ext}', f'<html xmlns="http://www.w3.org/1999/xhtml"><head><title>{title}</title></head><body><h1>{title}</h1><p>{text}</p></body></html>')
results={}
for side, checkout in [('before',sys.argv[1]), ('after',sys.argv[2])]:
    sha=subprocess.check_output(['git','rev-parse','HEAD'], cwd=checkout,text=True).strip()
    transcript=f'T3 Code | EPUB attachment text extraction\n{side.upper()} | commit {sha}\nLinux | Node CLI | identical synthetic EPUB 3 books\n\n'
    results[side]={}
    for ext in ['xhtml','xht']:
        args=['node','apps/server/src/bin.ts','__document-text',str(out/f'chapters-{ext}.epub'),'.epub']
        p=subprocess.run(args,cwd=checkout,capture_output=True,text=True)
        transcript+=f'$ node apps/server/src/bin.ts __document-text chapters-{ext}.epub .epub\n'+p.stdout+f'\nExit code: {p.returncode}\n\n'
        results[side][ext]={'stdout':p.stdout,'stderr':p.stderr,'exit':p.returncode}
    (out/f'{side}.txt').write_text(transcript)
(out/'results.json').write_text(json.dumps(results,indent=2))
print(out)
print(json.dumps(results,indent=2))
