from pathlib import Path
import jinja2
from reportsjob import ReportJobError, get_valid_filename
import os
import json


def run(template: str, datafile: str, format: str, output: str) -> list:
    generated_file_list = []
    output_path = Path(output)
    os.makedirs(str(output_path), exist_ok=True)

    with open(datafile, 'r', encoding='utf8') as f:
        s = f.read()
    json_data = json.loads(s)
    if not 'items' in json_data:
        raise ReportJobError("Invalid JSON File [expected 'items' property]")

    if not 'meta' in json_data:
        raise ReportJobError("Invalid JSON File [expected 'meta' property]")

    #    if not 'filename' in json_data['meta']:
    #	    raise ReportJobError("Invalid JSON File [expected 'meta.filename' property]")

    meta = json_data['meta']

    for idx, item in enumerate(json_data['items']):
        #        fname = json_data['meta']['filename']
        #        fname = fname.format(**item)
        #        fname = get_valid_filename(fname)
        report_page_data = {
            "meta": meta,
            "data": item
        }

        with open(template, 'r', encoding='utf8') as f:
            report_template = jinja2.Template(f.read())
        output_data = report_template.render(report_page_data)
        prog = int(idx + 1)
        fname = str(prog) + '.html'
        fulloutputfilename = str(output_path.joinpath(fname))
        with open(fulloutputfilename, 'w', encoding='utf8') as f:
            f.write(output_data)
        generated_file_list += [fname]

    return generated_file_list
