import os
import subprocess
import time
from . import res

DEFAULT_PARAMS_AV1 = "tune=0"

PRESETS_AV1 = [str(i) for i in range(6, 3, -1)]
CRFS_AV1 = [str(i) for i in range(30, 9, -1)]

def get_encoding_command_av1(f, preset, crf):
    filenameSample = os.path.splitext(os.path.basename(f))[0]
    filenameEncode = ".".join(
        [
            filenameSample,
            'AV1',
            '10Bit',
            'Preset',
            f'{preset}',
            'CRF',
            f'{crf}',
            'mkv'
        ]
    )
    filepathEncode = os.path.join(res.get_path_data_encodes_av1(), filenameEncode)

    cmd_parts = [
        'ffmpeg',
        f'-i "{f}"',
        '-an',
        '-c:v libsvtav1',
        f'-preset {preset}',
        f'-crf {crf}',
        f'-svtav1-params "{DEFAULT_PARAMS_AV1}"',
        f'-pix_fmt yuv420p10le',
        '-g 245',
        '-y',
        f'"{filepathEncode}"'
    ]
    
    return " ".join(cmd_parts)

def start_workflow():
    res.bootstrap_folder_structure()

    path_results_encoding_time_av1_json = os.path.join(
        res.get_path_results_encoding_time(),
        res.get_filename_results_encoding_time_av1()
    )
    results_encoding_time_av1 = res.read_dict_from_json_file(
        path_results_encoding_time_av1_json
    )

    for preset in PRESETS_AV1:
        if not preset in results_encoding_time_av1.keys():
            results_encoding_time_av1[preset] = {}
        for crf in CRFS_AV1:
            if not crf in results_encoding_time_av1[preset].keys():
                results_encoding_time_av1[preset][crf] = {}
            for f in res.get_all_sample_files():
                filename = os.path.splitext(os.path.basename(f))[0]
                if filename in results_encoding_time_av1[preset][crf].keys():
                    continue

                time_start = time.time()
                subprocess.run(
                    get_encoding_command_av1(f, preset, crf),
                    shell=True,
                    check=True
                )
                time_encoding = round(time.time() - time_start)
                
                results_encoding_time_av1[preset][crf][filename] = time_encoding

                res.write_dict_to_json_file(
                    path_results_encoding_time_av1_json,
                    results_encoding_time_av1
                )
        