#!/usr/bin/env python3
"""Print FWS texts in the language of the environment.

Usage:
  fws-i18n [--catalog NAME] <key> [name=value ...]
  fws-i18n --catalog NAME --shell <namespace>...
  fws-i18n --catalog NAME --render <file>

The first form prints one text: the live session (/root/.xinitrc) uses it for
the dialogs shown after the installer has closed. The catalog defaults to
"installer"; "system" holds the texts of the FWS tools.

--shell prints Bash assignments of every text of the given namespaces into the
associative array FWS_T, placeholders left in: /usr/local/lib/fws/i18n.sh loads
them once per script instead of starting Python for every message.

--render prints <file> with each {{t:key}} replaced by its text. The installer
uses it on the desktop configuration files it copies into the home folders.
Texts are escaped for JSON in a .json file; elsewhere their straight quotes are
made typographic, since these files embed them in quoted shell arguments.
"""

import json
import re
import shlex
import sys

sys.path.insert(0, "/usr/local/lib/fws")

MARKER = re.compile(r"\{\{t:([a-z0-9_]+(?:\.[a-z0-9_]+)+)\}\}")
TYPOGRAPHIC_QUOTES = str.maketrans({"'": "’", '"': "”"})


def shell_assignments(catalog, namespaces):
    lines = ["declare -gA FWS_T"]
    for key in sorted(catalog.messages()):
        if key.split(".", 1)[0] in namespaces:
            text = catalog.text(key)
            if text is not None:
                lines.append(f"FWS_T[{key}]={shlex.quote(text)}")
    return "\n".join(lines)


def render(catalog, path):
    with open(path, encoding="utf-8") as fh:
        content = fh.read()
    as_json = path.endswith(".json")

    def replace(match):
        text = catalog.t(match.group(1))
        if as_json:
            return json.dumps(text, ensure_ascii=False)[1:-1]
        return text.translate(TYPOGRAPHIC_QUOTES)

    return MARKER.sub(replace, content)


def main(argv):
    name = "installer"
    if len(argv) >= 2 and argv[0] == "--catalog":
        name, argv = argv[1], argv[2:]
    if not argv:
        print(__doc__.strip().splitlines()[2], file=sys.stderr)
        return 2
    try:
        import fws_i18n
        catalog = fws_i18n.catalog(name)
    except Exception as exc:  # pylint: disable=broad-except
        print(f"fws-i18n: {exc}", file=sys.stderr)
        catalog = None

    if argv[0] == "--shell":
        # An empty array still lets the scripts run: they show keys then.
        print(shell_assignments(catalog, set(argv[1:])) if catalog
              else "declare -gA FWS_T")
        return 0
    if argv[0] == "--render":
        if len(argv) != 2 or catalog is None:
            return 2
        sys.stdout.write(render(catalog, argv[1]))
        return 0

    key = argv[0]
    fields = dict(arg.split("=", 1) for arg in argv[1:] if "=" in arg)
    # A dialog with the key in it beats no dialog at all.
    print(catalog.t(key, **fields) if catalog else key)
    return 0


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