# --------------------------------------------------------------------------------------------------
# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2024 Jayesh Badwaik <j.badwaik@fz-juelich.de>
# --------------------------------------------------------------------------------------------------

import os
import tempfile
import shutil
import subprocess


def generate(input_dir, pipeline_array, prefix_array, output_filename, share_dir, tmp_dir):
    texdir = os.path.join(share_dir, "jureap/tex/jedi")
    tmpdir = tempfile.mkdtemp(dir=tmp_dir, prefix="exacb.tmp.")
    docdir = os.path.join(tmpdir, "jedi")

    # Match pipeline and prefix
    piprefix = {}
    for index, pipeline in enumerate(pipeline_array):
        piprefix[pipeline] = prefix_array[index]

    # Copy Template Files
    shutil.copytree(texdir, docdir)

    for pipeline in piprefix:
        prefixed = [filename for filename in os.listdir(input_dir) if filename.startswith(pipeline)]

        plot_filename = os.path.join(docdir, "plot.tex")
        with open(plot_filename, "w") as plotfile:
            plotfile.write("% This file is generated by jureap\n")

        table_filename = os.path.join(docdir, "table.tex")
        with open(table_filename, "w") as tablefile:
            tablefile.write("% This file is generated by jureap\n")

        json_filename = os.path.join(docdir, "json.tex")
        with open(json_filename, "w") as jsonfile:
            jsonfile.write("% This file is generated by jureap\n")

        author_filename = os.path.join(docdir, "author.tex")
        with open(author_filename, "w") as authorfile:
            authorfile.write("% This file is generated by jureap\n")
            authorfile.write("\\title{JEDI Report}\n")

    subprocess.run(["make"], cwd=docdir, env=os.environ)
    shutil.copyfile(os.path.join(docdir, "report.pdf"), output_filename)
