import os
from . import res

def start_workflow():
    res.bootstrap_folder_structure()

    aggregated_metrics = {}
    output_file = os.path.join(
        res.get_path_results_aggregations(),
        res.get_filename_results_aggregations_hevc()
    )

    for f in res.get_all_encoded_files_hevc():
        filename        = os.path.splitext(os.path.basename(f))[0]
        sampleNumber    = res.get_sample_number_from_filename(filename)
        preset          = res.get_preset_from_encode_filename(filename)
        crf             = res.get_crf_from_encode_filename(filename)

        if not preset in aggregated_metrics.keys():
            aggregated_metrics[preset] = {}
        if not crf in aggregated_metrics[preset].keys():
            aggregated_metrics[preset][crf] = {}
        if not "samples" in aggregated_metrics[preset][crf].keys():
            aggregated_metrics[preset][crf]["samples"] = {}

        aggregated_metrics[preset][crf]["samples"][sampleNumber] = {
            "encoding_time": res.get_encoding_time_hevc(filename),
            "filesize_percentage": res.get_filesize_percentage(f),
            "vmaf_score": res.get_vmaf_score_of_encode(filename)
        }

    for preset in aggregated_metrics.keys():
        for crf in aggregated_metrics[preset].keys():
            aggregated_metrics[preset][crf] = res.aggregated_metrics(
                aggregated_metrics[preset][crf]
            )

    res.write_dict_to_json_file(output_file, aggregated_metrics)
        
    