from ast import Num
import re
import subprocess
import sys
from pathlib import Path
import os
from time import sleep
output_folder_name = "/quality_test_out/"
droppedFile = sys.argv[1]
droppedName = Path(droppedFile).name
originalfiles = sys.orig_argv[2:]

#long path shenanigans 
joined = (' '.join(originalfiles))
re.sub (' +', ' ', joined)
listed = re.split(r'(.+?mkv)', joined)
listed = list(filter(None, listed))
listed = [i.lstrip() for i in listed]

#droppedFile = ['ORIGINAL_COMP_0Episode 00 - Ninovo.mkv']

#get path of script location and remove the tail
head_tail = os.path.split(sys.argv[0])
output_path = head_tail[0]


#skip first part of sys.argv since it points to script location
arguments = sys.argv[1:]

#check if output folder exists, otherwise create it
isExist = os.path.exists(output_path+output_folder_name)
if not isExist:
    os.makedirs(output_path+output_folder_name)

#droppedFile = ["sam_overlord_bluraysource.mkv"]

def subproc_ffmpeg(file="",crf_value="", output_path="", output_folder_name=""):
    basename = os.path.basename(file)
    print(basename)
    print(file)
    print("printing output path: ", output_path)
    print("printing folder_name: ", output_folder_name)
    return 'ffmpeg.exe -i "{file}" -map 0:v -c:v libx265 -preset slow -crf "{crf_value}" -x265-params "no-sao=1:bframes=8:psy-rd=2:psy-rdoq=1.5:aq-mode=3:ref=6" -pix_fmt yuv420p10le -map 0:a -c:a libopus -ac 6 -b:a 576k -f matroska "{output_path}{output_folder_name}crf-{crf_value}_{basename}"'.format(file=file, crf_value=crf_value, output_path=output_path, output_folder_name=output_folder_name,  basename=basename)

print("CRF granuality? 1 or 0.1: ")
while True:
    crf_gran=float(input("> "))
    if crf_gran == 1:
        large_gran = True
        print("Stepping in whole values")
        break
    if crf_gran == 0.1:
        large_gran = False
        print("stepping in decimal values")
        break
    print("Invalid choice, try again")




crf_range = [int(z) for z in input ("CRF range to test? Seperate with dash (eg: 15-17): ").split('-')]
print(crf_range)
if large_gran == True:
    while crf_range[0] <= crf_range[1]:
        crf_value = crf_range[0]
        for file in listed:

            subprocess.run(subproc_ffmpeg(file, crf_value, output_path, output_folder_name))
        crf_range[0] += 1
if large_gran == False:
    while crf_range[0] < crf_range[1]:
        crf_value = round(crf_range[0], 1)
        for file in listed:

            subprocess.run(subproc_ffmpeg(file, crf_value, output_path, output_folder_name), creationflags=0x00004000)
        crf_range[0] += 0.1





        



   

input("press enter to exit") 