import os
import subprocess
from . import res

def start_workflow():
    res.bootstrap_folder_structure()

    # hevc diagrams
    hevc_diagrams = res.get_diagrams_hevc()

    # to complete data structure for rendering
    data = {
        "aggregated_metrics": {
            "hevc": {
                "encoding_time": {},
                "filesize_percentage": {},
                "vmaf_score": {}
            }
        },
        "diagrams": {
            "hevc": {
                "encoding_time": hevc_diagrams["encoding_time"],
                "filesize_percentage": hevc_diagrams["filesize_percentage"],
                "vmaf_score": hevc_diagrams["vmaf_score"]
            }
        }
    }

    # hevc metrics
    aggregated_metrics_hevc = res.read_dict_from_json_file(
        os.path.join(
            res.get_path_results_aggregations(),
            res.get_filename_results_aggregations_hevc()
        )
    )
    for preset in aggregated_metrics_hevc.keys():
        for crf in aggregated_metrics_hevc[preset].keys():
            data["aggregated_metrics"]["hevc"]["encoding_time"]["mean"] = round(
                aggregated_metrics_hevc[preset][crf]["encoding_time"]["mean"],
                2
            )
            data["aggregated_metrics"]["hevc"]["encoding_time"]["median"] = round(
                aggregated_metrics_hevc[preset][crf]["encoding_time"]["median"],
                2
            )
            data["aggregated_metrics"]["hevc"]["filesize_percentage"]["mean"] = round(
                aggregated_metrics_hevc[preset][crf]["filesize_percentage"]["mean"],
                2
            )
            data["aggregated_metrics"]["hevc"]["filesize_percentage"]["median"] = round(
                aggregated_metrics_hevc[preset][crf]["filesize_percentage"]["median"],
                2
            )
            data["aggregated_metrics"]["hevc"]["vmaf_score"]["mean"] = round(
                aggregated_metrics_hevc[preset][crf]["vmaf_score"]["mean"],
                2
            )
            data["aggregated_metrics"]["hevc"]["vmaf_score"]["median"] = round(
                aggregated_metrics_hevc[preset][crf]["vmaf_score"]["median"],
                2
            )

    # av1 metrics
    data["aggregated_metrics"]["av1"] = res.read_dict_from_json_file(
        os.path.join(
            res.get_path_results_aggregations(),
            res.get_filename_results_aggregations_av1()
        )
    )

    # render the template
    res.render_template(
        os.path.join(res.get_path_templates(), "README.md.tmpl"),
        os.path.join(res.get_path_project(), "README.md"),
        data
    )