#!/usr/bin/env python3
import sys
import os
import jinja2


def main():
    if len(sys.argv) < 3:
        print(f"Usage: {sys.argv[0]} <input_template> <output_file>", file=sys.stderr)
        sys.exit(1)

    input_template = sys.argv[1]
    output_file = sys.argv[2]

    # We resolve included files relative to the input template's directory.
    search_dir = os.path.dirname(os.path.abspath(input_template))

    # Set up jinja2 environment with custom delimiters.
    #
    # Delimiters are changed to avoid conflict with Mustache tags like
    # {{ merchant_backend }}: the output of this step is a Mustache
    # template rendered later by libtalertemplating, so {{ ... }} has to
    # survive verbatim.  The replacements have to be sequences that do
    # not occur in HTML, CSS or JavaScript; '@<' and '@#' are safe, and
    # note that CSS at-rules ('@media', '@keyframes') are not, so the
    # single-character '@' can never become a delimiter here.
    #
    # StrictUndefined makes a mistyped '@@ name @@' an error rather than
    # an empty string, and keep_trailing_newline keeps the file ending
    # in a newline the way the source template does.
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(search_dir),
        variable_start_string="@@",
        variable_end_string="@@",
        block_start_string="@<",
        block_end_string=">@",
        comment_start_string="@#",
        comment_end_string="#@",
        undefined=jinja2.StrictUndefined,
        keep_trailing_newline=True,
    )

    template_name = os.path.basename(input_template)
    template = env.get_template(template_name)

    rendered = template.render()

    if not rendered.strip():
        print(f"{input_template} rendered to nothing", file=sys.stderr)
        sys.exit(1)

    # Ensure parent directory of output_file exists (especially in build directories).
    os.makedirs(os.path.dirname(os.path.abspath(output_file)), exist_ok=True)

    with open(output_file, "w", encoding="utf-8") as f:
        f.write(rendered)


if __name__ == "__main__":
    main()
