#!/usr/bin/env python3
import json
import os
import shlex
import subprocess

DOMAIN = "stillcontrol"
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
POT = os.path.join(ROOT, "po", f"{DOMAIN}.pot")


def quoted(value):
    return repr(value)


def collect_json_strings():
    settings_dir = os.path.join(ROOT, "UIs", "settings")
    lines = ["from gettext import gettext as _\n"]

    for filename in sorted(os.listdir(settings_dir)):
        if not filename.endswith(".json"):
            continue

        path = os.path.join(settings_dir, filename)
        with open(path, encoding="utf-8") as handle:
            data = json.load(handle)

        def walk(value):
            if isinstance(value, dict):
                for key, item in value.items():
                    if key in {"title", "subtitle", "message", "tooltip"} and isinstance(item, str):
                        lines.append(f"_({quoted(item)})\n")
                    elif key == "options" and isinstance(item, list):
                        for option in item:
                            if isinstance(option, list):
                                for label in option[0::2]:
                                    if isinstance(label, str):
                                        lines.append(f"_({quoted(label)})\n")
                    else:
                        walk(item)
            elif isinstance(value, list):
                for item in value:
                    walk(item)

        walk(data)

    return "".join(lines)


def collect_layout_strings():
    layout_dir = os.path.join(ROOT, "layouts")
    lines = []

    for filename in sorted(os.listdir(layout_dir)):
        if not filename.endswith(".json"):
            continue

        path = os.path.join(layout_dir, filename)
        with open(path, encoding="utf-8") as handle:
            data = json.load(handle)

        name = data.get("name")
        if isinstance(name, str):
            lines.append(f"_({quoted(name)})\n")

    lines.append("_('Custom')\n")
    return "".join(lines)


def run(command):
    print("+", " ".join(shlex.quote(part) for part in command))
    subprocess.run(command, check=True, cwd=ROOT)


json_source_path = os.path.join(ROOT, "po", ".settings-json.py")
with open(json_source_path, "w", encoding="utf-8") as json_source:
    json_source.write(collect_json_strings())
    json_source.write(collect_layout_strings())

try:
    python_files = sorted(
        os.path.join(ROOT, name)
        for name in os.listdir(ROOT)
        if name.endswith(".py")
    )
    ui_files = sorted(
        os.path.join(ROOT, "UIs", name)
        for name in os.listdir(os.path.join(ROOT, "UIs"))
        if name.endswith(".ui")
    )

    run([
        "xgettext",
        "--from-code=UTF-8",
        "--language=Python",
        "--keyword=_",
        "--keyword=ngettext:1,2",
        "--package-name=stillControl",
        "--output", POT,
        os.path.relpath(json_source_path, ROOT),
        *(os.path.relpath(path, ROOT) for path in python_files),
    ])
    run([
        "xgettext",
        "--from-code=UTF-8",
        "--language=Glade",
        "--join-existing",
        "--output", POT,
        *(os.path.relpath(path, ROOT) for path in ui_files),
    ])
    run([
        "xgettext",
        "--from-code=UTF-8",
        "--language=Desktop",
        "--join-existing",
        "--output", POT,
        os.path.join("data", "stillControl.desktop"),
    ])
finally:
    os.unlink(json_source_path)
