#!/usr/bin/env python3

"""Starts mako with the classroom styling at the room's UI scale.

mako only reads ~/.config, and its measurements have to follow UI_SCALE,
so the packaged template is resolved into the session's runtime directory
and mako is pointed at the result.
"""

import os
import sys
from pathlib import Path

sys.path.insert(0, "/usr/local/lib/ekklesia-classroom")

from classroom_config import SHELL_SCALE, scaled  # noqa: E402

MAKO = "/usr/bin/mako"
TEMPLATE = Path("/etc/ekklesia-classroom/mako/config.in")

# The same measurements the template carries, at UI_SCALE=1.0.
MEASUREMENTS = {
    "font-size": 12,
    "radius": 18,
    "padding-v": 14,
    "padding-h": 18,
    "margin": 18,
    "width": 380,
    "height": 160,
    "icon-size": 48,
}


def runtime_directory():
    base = os.environ.get("XDG_RUNTIME_DIR") or "/tmp"

    directory = Path(base) / "ekklesia-classroom"
    directory.mkdir(parents=True, exist_ok=True)

    return directory


def render(scale):
    config = TEMPLATE.read_text()

    for token, value in MEASUREMENTS.items():
        config = config.replace(
            f"@{token}@",
            str(scaled(value, scale)),
        )

    return config


def main():
    scale = SHELL_SCALE

    try:
        path = runtime_directory() / "mako.config"
        path.write_text(render(scale))
        config_argument = str(path)
    except OSError as error:
        # Better plain notifications than none at all.
        print(
            f"classroom-notifications: falling back to the unscaled template: {error}",
            file=sys.stderr,
        )
        config_argument = str(TEMPLATE)

    os.execv(MAKO, [MAKO, "--config", config_argument])


if __name__ == "__main__":
    main()
