#!/usr/bin/env python3
# Inject whitepaper-specific CSS overrides into the rst2html5 output:
#
#   1. Embed the ChunkFive webfont (base64 woff2) and assign it to h1 /
#      h2, so whitepaper titles read in the same voice as the homepage
#      logo instead of docutils's default serif fallback.
#
#   2. Cancel docutils's responsive.css `body > *` rule for the
#      uncloseai floating button — that rule slaps `padding: 0.5rem
#      calc(29% - 7.2rem)` onto every direct child of <body>, which
#      blows the 121px button up to ~40% of the viewport width. Scoped
#      override plus `all: revert` so the button falls back to its own
#      stylesheet's intended sizing.
#
# Usage: inject-whitepaper-css.py <html-file> <chunkfive-woff2-path>

import base64
import os
import sys


TEMPLATE = """\
<style>
@font-face {{
  font-family: 'chunkfive';
  src: url(data:font/woff2;base64,{woff2_b64}) format('woff2');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}}
main > h1, main > h2, section > h2 {{
  font-family: 'chunkfive', Georgia, serif;
  font-weight: normal;
  letter-spacing: 0.01em;
}}
/* Declarative period on the whitepaper title picks up the same brand
   green (#227842) as the homepage "lumbda." period. */
h1.title .period {{
  color: #227842;
}}
/* docutils's responsive.css applies a blanket rule to every `body > *`
   that sets `background-color: white; line-height: 1.6; padding: 0.5rem
   calc(29% - 7.2rem); margin: auto; max-width: 100rem`. The uncloseai
   floating button gets appended to <body> and inherits those rules —
   exploding it to nearly half the viewport and painting its background
   white (which hides the black pill). Override just the damaged
   properties so uncloseai's own stylesheet still supplies position,
   width, height, background, border, and color. */
body > button#floating-ai-button,
body > .uncloseai-floating-button {{
  padding: 0 !important;
  margin: 0 !important;
  max-width: calc(100vw - 20px) !important;
  background-color: unset !important;
  line-height: normal !important;
}}
/* Click-to-zoom lightbox for diagrams. */
main img, section img {{
  cursor: zoom-in;
}}
.wp-lightbox {{
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.92);
  display: none;
  align-items: center;
  justify-content: center;
  z-index: 10001;
  cursor: zoom-out;
  padding: 1.5rem;
}}
.wp-lightbox.open {{ display: flex; }}
.wp-lightbox img {{
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.6);
}}
</style>
<script>
(function () {{
  if (window.__wpLightbox) return;
  window.__wpLightbox = true;
  document.addEventListener("DOMContentLoaded", function () {{
    var imgs = document.querySelectorAll("main img, section img");
    if (!imgs.length) return;
    var overlay = document.createElement("div");
    overlay.className = "wp-lightbox";
    var big = document.createElement("img");
    big.alt = "";
    overlay.appendChild(big);
    document.body.appendChild(overlay);
    function close() {{ overlay.classList.remove("open"); big.src = ""; }}
    overlay.addEventListener("click", close);
    document.addEventListener("keydown", function (e) {{
      if (e.key === "Escape") close();
    }});
    imgs.forEach(function (img) {{
      img.addEventListener("click", function () {{
        big.src = img.currentSrc || img.src;
        overlay.classList.add("open");
      }});
    }});
  }});
}})();
</script>
"""


def main(argv):
    if len(argv) != 3:
        sys.stderr.write("usage: inject-whitepaper-css.py <html-file> <chunkfive-woff2-path>\n")
        return 2
    html_path, woff2_path = argv[1], argv[2]
    if not os.path.isfile(woff2_path):
        sys.stderr.write(f"inject-whitepaper-css: chunkfive missing: {woff2_path}\n")
        return 1
    with open(woff2_path, "rb") as f:
        woff2_b64 = base64.b64encode(f.read()).decode()
    style_block = TEMPLATE.format(woff2_b64=woff2_b64)
    with open(html_path, "r") as f:
        html = f.read()
    if "</head>" not in html:
        sys.stderr.write("inject-whitepaper-css: no </head> found\n")
        return 1
    html = html.replace("</head>", style_block + "</head>", 1)
    # Wrap the trailing period on the `<h1 class="title">lumbda.</h1>`
    # heading in a span so CSS can color just the period green. Docutils
    # emits exactly this markup for the top-level RST title.
    html = html.replace(
        '<h1 class="title">lumbda.</h1>',
        '<h1 class="title">lumbda<span class="period" aria-hidden="true">.</span></h1>',
        1,
    )
    with open(html_path, "w") as f:
        f.write(html)
    print(f"inject-whitepaper-css: injected {len(style_block)} bytes into {html_path}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
