"""Typographie française hors <style>/<script> : espaces insécables, apostrophes courbes."""
import re

src = open("moteur.src.html", encoding="utf-8").read()
NB, FINE = " ", " "


def fix(t):
    t = t.replace(" :", NB + ":").replace(" ;", FINE + ";").replace(" ?", FINE + "?").replace(" !", FINE + "!")
    t = t.replace("'", "’").replace(" —", NB + "—").replace("≈ ", "≈" + NB).replace("&lt; ", "&lt;" + NB)
    t = t.replace(" × ", NB + "×" + NB).replace(" › ", NB + "› ")
    return re.sub(r"(\d) (ms|s|i/s|%)(?=[\s<.,)]|$)", lambda m: m.group(1) + NB + m.group(2), t)


parts = re.split(r"(<style>.*?</style>|<script>.*?</script>)", src, flags=re.S)
out = "".join(p if p.startswith(("<style>", "<script>")) else fix(p) for p in parts)
open("moteur.html", "w", encoding="utf-8").write(out)
text = re.sub(r"<style>.*?</style>|<script>.*?</script>", "", out, flags=re.S)
assert "'" not in text and not re.search(r"[\x00-\x08]", out)
assert "&lt; 8 ms" in out and "7,6 ms" in out
print("ok", len(out) // 1024, "Ko")

# version autonome pour un hébergement ordinaire (dl.haven47.fr) : l'artefact ajoute lui-même doctype, <head> et
# charset ; un serveur Apache qui envoie « text/html » sans charset ferait lire l'UTF-8 en Windows-1252 (accents cassés)
head, sep, body = out.partition("</style>\n")
assert sep, "fin du <style> introuvable"
import base64, os, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "logo"))
from logo_export import svg_symbol
icon = base64.b64encode(svg_symbol("hf").encode("utf-8")).decode("ascii")          # symbole en icône d'onglet
web = ('<!doctype html>\n<html lang="fr">\n<head>\n<meta charset="utf-8">\n'
       '<meta name="viewport" content="width=device-width,initial-scale=1">\n'
       + head + sep + '<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,' + icon + '">\n'
       + "</head>\n<body>\n" + body.rstrip("\n") + "\n</body>\n</html>\n")
os.makedirs("web", exist_ok=True)
open("web/moteur.html", "w", encoding="utf-8", newline="\n").write(web)
assert web.index('<meta charset="utf-8">') < 1024
print("web/moteur.html", len(web.encode("utf-8")) // 1024, "Ko")
