#! /usr/bin/env python3

"""
Tool to evaluate a given Jinja2 template with the given JSON which is passed as
'data' in the environment.

Very much a poor clone of j2cli but with the one feature that it can handle JSON
that is an array, as j2cli assumes the JSON is a dictionary.

Copyright (C) 2021 Ross Burton
Licensed under the MIT License
"""

import argparse
import json
import sys

import jinja2

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("template", type=argparse.FileType('r'), metavar="TEMPLATE")
    parser.add_argument("json", type=argparse.FileType('r'), metavar="JSON")
    parser.add_argument("output", type=argparse.FileType("w"), metavar="OUTPUT", nargs="?", default=sys.stdout)
    args = parser.parse_args()

    source = args.template.read()
    env = jinja2.Environment(loader=jinja2.BaseLoader(), autoescape=jinja2.select_autoescape())
    template = env.from_string(source)

    data = json.load(args.json)
    args.output.write(template.render({"data": data}))
