#!/usr/bin/env python3
"""Builds the Leciaura website.

    python3 build.py

Reads   src/layout.html      shared header, navigation and footer
        src/pages/*.html     one file per page (title and description at the top)
        i18n/<lang>.json     optional translations, e.g. i18n/de.json
Writes  site/*.html          English pages (the controlling version)
        site/<lang>/*.html   one folder per translated language
        i18n/strings.json    every piece of English text on the site, ready to translate

A language only appears in the site's language menu once its file exists in i18n/.
Any text missing from a translation file stays in English.
"""
import json, re, sys
from pathlib import Path

ROOT = Path(__file__).parent
SRC, SITE, I18N = ROOT / "src", ROOT / "site", ROOT / "i18n"
LANG_NAMES = {"en": "English", "de": "Deutsch", "nl": "Nederlands", "es": "Español",
              "it": "Italiano", "vi": "Tiếng Việt", "id": "Bahasa Indonesia", "ko": "한국어"}
ATTRS = ("alt", "placeholder", "aria-label", "content", "data-label", "data-wa",
         "data-msg-required", "data-msg-email", "data-msg-phone", "data-msg-consent", "data-msg-fail")
DOMAIN = "https://www.leciaura.com/"
SKIP = re.compile(r"(<script\b.*?</script>|<style\b.*?</style>)", re.S | re.I)
TEXT = re.compile(r">([^<>]+)<")
ATTR = re.compile(r'\b(%s)="([^"]*)"' % "|".join(ATTRS))
NOTICE = ("This page was machine translated and has not yet been reviewed. "
          "The English version, including all specifications and legal statements, is the controlling version.")


def translatable(s):
    s = s.strip()
    return bool(s) and bool(re.search(r"[A-Za-z]{2}", s)) and not s.startswith(("http", "#", "width="))


def walk(html, fn):
    """Apply fn to every visible text run and translatable attribute value."""
    out = []
    for i, part in enumerate(SKIP.split(html)):
        if i % 2:
            out.append(part)
            continue
        def text(m):
            raw = m.group(1)
            core = raw.strip()
            if not translatable(core):
                return m.group(0)
            return ">" + raw.replace(core, fn(core)) + "<"
        def attr(m):
            val = m.group(2)
            if m.group(1) == "content" and " " not in val:
                return m.group(0)
            return '%s="%s"' % (m.group(1), fn(val) if translatable(val) else val)
        out.append(ATTR.sub(attr, TEXT.sub(text, part)))
    return "".join(out)


def load_pages():
    pages = []
    for f in sorted((SRC / "pages").glob("*.html")):
        head, body = f.read_text(encoding="utf-8").split("\n---\n", 1)
        meta = dict(line.split(":", 1) for line in head.strip().splitlines())
        pages.append((f.name, {k.strip(): v.strip() for k, v in meta.items()}, body))
    return pages


def render(layout, name, meta, body, lang, langs):
    root = "" if lang == "en" else "../"
    path = ("" if lang == "en" else lang + "/") + ("" if name == "index.html" else name)
    html = layout.replace("{{content}}", body)
    menu = hreflang = notice = ""
    if len(langs) > 1:
        def url(l):
            return ("" if l == "en" else l + "/") + name
        items = "".join('<li><a href="%s%s" lang="%s"%s>%s</a></li>' % (
            root, url(l), l, ' aria-current="true"' if l == lang else "", LANG_NAMES.get(l, l)) for l in langs)
        menu = ('<details class="lang"><summary aria-label="Language">%s</summary><ul>%s</ul></details>'
                % (lang.upper(), items))
        hreflang = "\n".join('<link rel="alternate" hreflang="%s" href="https://www.leciaura.com/%s">' % (l, url(l))
                             for l in langs)
        if lang != "en":
            notice = '<div class="mt-notice"><div class="wrap">%s <a href="../%s">English</a></div></div>' % (NOTICE, name)
    robots = '<meta name="robots" content="%s">\n' % meta["robots"] if meta.get("robots") else ""
    for key, val in {"lang": lang, "title": meta["title"], "desc": meta["desc"], "root": root, "path": path, "robots": robots,
                     "langmenu": menu, "hreflang": hreflang, "mtnotice": notice}.items():
        html = html.replace("{{%s}}" % key, val)
    # mark the current page in the navigation
    html = html.replace('<li><a href="%s">' % name, '<li><a href="%s" aria-current="page">' % name)
    return html


def main():
    layout = (SRC / "layout.html").read_text(encoding="utf-8")
    pages = load_pages()
    catalogs = {f.stem: json.loads(f.read_text(encoding="utf-8"))
                for f in sorted(I18N.glob("*.json")) if f.stem != "strings"}
    langs = ["en"] + [l for l in catalogs if l in LANG_NAMES]
    strings = []

    def collect(s):
        if s not in strings:
            strings.append(s)
        return s

    for name, meta, body in pages:
        html = render(layout, name, meta, body, "en", langs)
        walk(html, collect)
        (SITE / name).write_text(html, encoding="utf-8")
        for lang in langs[1:]:
            cat = catalogs[lang]
            out = walk(render(layout, name, meta, body, lang, langs), lambda s: cat.get(s) or s)
            (SITE / lang).mkdir(exist_ok=True)
            (SITE / lang / name).write_text(out, encoding="utf-8")

    # sitemap.xml and robots.txt for search engines
    urls = []
    for name, meta, _ in pages:
        if meta.get("robots"):
            continue
        for lang in langs:
            urls.append(DOMAIN + ("" if lang == "en" else lang + "/") + ("" if name == "index.html" else name))
    (SITE / "sitemap.xml").write_text(
        '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
        + "".join("  <url><loc>%s</loc></url>\n" % u for u in urls) + "</urlset>\n", encoding="utf-8")
    (SITE / "robots.txt").write_text("User-agent: *\nAllow: /\n\nSitemap: %ssitemap.xml\n" % DOMAIN, encoding="utf-8")

    I18N.mkdir(exist_ok=True)
    (I18N / "strings.json").write_text(json.dumps({s: "" for s in strings}, ensure_ascii=False, indent=1), encoding="utf-8")
    print("Built %d pages in: %s. %d strings listed in i18n/strings.json" % (len(pages), ", ".join(langs), len(strings)))
    for lang in langs[1:]:
        missing = [s for s in strings if not catalogs[lang].get(s)]
        if missing:
            print("  %s: %d strings not translated yet (shown in English)" % (lang, len(missing)))


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