"""Build a house decision deck from body.html (In Motion Automation deck kit, Rev 2, 4 Nov 2026).

Copy this folder into a report pack as <pack>/deck-build/, set the four values under CONFIG,
write body.html (start from the kit's body.html) and sources.py, then run:

    python3 build.py && ./export.sh

Pack layout the build expects:
    <pack>/figures/<name>.png       report figures (same files as the paper)
    <pack>/assets/deck/<name>.jpg   stills, 1800 px long side, JPEG quality about 78
    <pack>/deck-build/              this kit

Markers in body.html:
    {{s:key}}     numbered source, numbered by first appearance (keys in sources.py)
    {{fig:name}}  figure PNG from ../figures, embedded, at the height set in FIGH (px)
    {{img:name}}  still from ../assets/deck/<name>.jpg, embedded as a data URL
    {{LOGO}}      cover mark (logo.html)
    {{SOURCES}}   the numbered source list for the last slide
The output is one self-contained HTML file that opens offline.
"""
import base64
import html
import re
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
PACK = HERE.parent
sys.path.insert(0, str(HERE))
from sources import SOURCES  # noqa: E402

# ---------------------------------------------------------------- CONFIG
OUT = PACK / "EXAMPLE-DECK.html"          # <PACK-NAME>-DECK.html
TITLE = "Example Deck"                    # browser tab title, two to four words
BUILT_FROM = "the report in this pack"    # e.g. "MARKET-STUDY.tex in this pack"
FIGH = {"example-house-chart": 300}       # figure name -> height in px; default 330
# ------------------------------------------------------------------------


def fig(name):
    data = base64.b64encode((PACK / "figures" / f"{name}.png").read_bytes()).decode()
    h = FIGH.get(name, 330)
    return (f'<img class="fx" style="height:{h}px;width:auto" '
            f'src="data:image/png;base64,{data}" alt="Report figure: {name}">')


def img(name):
    data = base64.b64encode((PACK / "assets" / "deck" / f"{name}.jpg").read_bytes()).decode()
    return f"data:image/jpeg;base64,{data}"


def main():
    body = (HERE / "body.html").read_text()
    order = []
    for k in re.findall(r"\{\{s:([A-Za-z0-9]+)\}\}", body):
        if k not in SOURCES:
            raise SystemExit("unknown source " + k)
        if k not in order:
            order.append(k)
    n = {k: i + 1 for i, k in enumerate(order)}
    body = re.sub(r"\{\{s:([A-Za-z0-9]+)\}\}", lambda m: f"[{n[m.group(1)]}]", body)
    body = re.sub(r"\{\{fig:([\w-]+)\}\}", lambda m: fig(m.group(1)), body)
    body = re.sub(r"\{\{img:([\w-]+)\}\}", lambda m: img(m.group(1)), body)
    body = body.replace("{{LOGO}}", (HERE / "logo.html").read_text().strip())
    entries = []
    for k in order:
        pub, title, date, url, lab = SOURCES[k]
        links = ""
        if url:
            disp = re.sub(r"^https?://(www\.)?", "", url)
            links = f'<a href="{html.escape(url)}">{html.escape(disp)}</a>'
        labs = f' <span class="tag2">({lab})</span>' if lab else ""
        d = f" {date}." if date else ""
        t = title if title.endswith(("?", ".", ")")) else title + "."
        entries.append(f"<p><b>[{n[k]}]</b>{pub}. {t}{d}{labs} {links}</p>")
    body = body.replace("{{SOURCES}}", "\n      ".join(entries))
    assert "{{" not in body, re.findall(r"\{\{[^}]*\}\}", body)[:5]
    own = HERE / "deck-own.css"
    css = [(HERE / "fonts.css").read_text(), (HERE / "base.css").read_text(),
           (HERE / "deck.css").read_text()]
    if own.exists():
        css.append(own.read_text())
    head = f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{TITLE}</title>
<!--
  In Motion Automation decision deck, true 16:9 (13.333in x 7.5in), cool vibe, deck kit Rev 2.
  Prose follows the house writing lock (jake-house-writing).
  Built from {BUILT_FROM}; charts are the report's figures (same files).
-->
<style>
{chr(10).join(css)}
</style>
</head>
<body class="ima-doc ima-cool">

"""
    out = head + body + "\n</body>\n</html>\n"
    OUT.write_text(out)
    print("sources:", len(order), "bytes:", len(out), "->", OUT.name)


if __name__ == "__main__":
    main()
