#!/usr/bin/env python3
"""Compile all Bibel der Opfer HTML chapters into a single EPUB."""
import os, re
from ebooklib import epub

WORKSPACE = "/home/hermes/workspace"

chapters = [
    ("kapitel_01", "Die perfekte Opferkampagne"),
    ("kapitel_02", "Der Schalter, der nie auf Mitte steht"),
    ("kapitel_03", "Drei Kulturen, eine Verschiebung"),
    ("kapitel_04", "Competitive Victimhood"),
    ("kapitel_05", "DARVO"),
    ("kapitel_06", "Virtuous Victim Signaling"),
    ("kapitel_07", "Die Umkehrung"),
    ("kapitel_08", "Gegenmittel"),
]

book = epub.EpubBook()
book.set_identifier("bibel-der-opfer-001")
book.set_title("Die Bibel der Opfer")
book.set_language("de")
book.add_author("Daniel Krause")

# Extract common CSS from first chapter
first_path = os.path.join(WORKSPACE, "bibel_der_opfer_kapitel_01.html")
with open(first_path) as f:
    first_raw = f.read()
css_match = re.search(r"<style>(.*?)</style>", first_raw, re.DOTALL)
css = css_match.group(1) if css_match else "body { font-family: serif; }"

# Add CSS as a stylesheet
style_item = epub.EpubItem(uid="style", file_name="style/default.css", media_type="text/css", content=css.encode("utf-8"))
book.add_item(style_item)

epub_chapters = []
for slug, title in chapters:
    path = os.path.join(WORKSPACE, f"bibel_der_opfer_{slug}.html")
    with open(path) as f:
        raw = f.read()
    body_match = re.search(r"<body>(.*?)</body>", raw, re.DOTALL)
    body_html = body_match.group(1) if body_match else raw
    
    ch = epub.EpubHtml(title=title, file_name=f"{slug}.xhtml", lang="de")
    ch.content = f"""<!DOCTYPE html>
<html lang="de">
<head><link rel="stylesheet" type="text/css" href="style/default.css"/></head>
<body>{body_html}</body>
</html>"""
    ch.add_item(style_item)
    book.add_item(ch)
    epub_chapters.append(ch)

# Build spine
book.spine = ["nav"] + epub_chapters

# Build TOC
book.toc = [epub.Link(f"{slug}.xhtml", title, slug) for slug, title in chapters]

# Navigation
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())

# Write
outpath = os.path.join(WORKSPACE, "bibel_der_opfer.epub")
epub.write_epub(outpath, book)
fsize = os.path.getsize(outpath)
print(f"EPUB: {outpath}")
print(f"Size: {fsize:,} bytes")
print("Done!")
