import os


def fixed_split(videos, thresholds, mask_suffix, overlap=0, background_path="/"):


    # crop target background video frames
    backgrounds = [os.path.join(background_path, f[:-4]) for f in os.listdir(background_path) if f.endswith(".mp4")]
    print(f"Splitting {len(backgrounds)} target background videos vertically by a fixed threshold")

    for i, background in enumerate(backgrounds):
        if i >= (len(thresholds)) or not thresholds[i]:
            continue

        try:
            os.makedirs(background + "_up")
            os.makedirs(background + "_dw")
        except FileExistsError:
            continue
        
        threshold = int(thresholds[i])
        iup_region = f"iw:{threshold + overlap}:0:0"
        idw_region = f"iw:ih-{threshold + overlap}:0:{threshold - overlap}"

        cmd=(
            f"ffmpeg -i \"{os.path.join(background, '%04d_img.png')}\" "
            f'-filter:v "crop={iup_region}" '
            f"\"{os.path.join(background+'_up', '%04d_img.png')}\""
            " > split_background_logs.txt 2>&1"
        )
        code = os.system(
            cmd
        )
        if code != 0:
            exit(code)
        code = os.system(
            f"ffmpeg -i \"{os.path.join(background, '%04d_img.png')}\" "
            f'-filter:v "crop={idw_region}" '
            f"\"{os.path.join(background+'_dw', '%04d_img.png')}\""
            " > split_background_logs.txt 2>&1"
        )
        if code != 0:
            exit(code)

    print(f"Splitting {len(videos)} videos vertically by a fixed threshold")
    for i, video in enumerate(videos):
        if i >= (len(thresholds)) or not thresholds[i]:
            continue

        try:
            os.makedirs(video + "_up")
            os.makedirs(video + "_dw")
        except FileExistsError:
            continue

        threshold = int(thresholds[i])
        iup_region = f"iw:{threshold + overlap}:0:0"
        idw_region = f"iw:ih-{threshold + overlap}:0:{threshold - overlap}"

        # crop target background single image
        cmd = (
            f"ffmpeg -y -i \"{video+'.png'}\" "
            f'-filter:v \"crop={iup_region}\" '
            f"\"{video+'_up.png'}\""
            " > split_logs.txt 2>&1"
        )
        code = os.system(
            cmd
        )
        if code != 0:
            exit(code)
        code = os.system(
            f"ffmpeg -y -i \"{video+'.png'}\" "
            f'-filter:v "crop={idw_region}" '
            f"\"{video+'_dw.png'}\""
            " > split_logs.txt 2>&1"
        )
        if code != 0:
            exit(code)


        # crop color images
        cmd=(
            f"ffmpeg -i \"{os.path.join(video, '%04d_img.png')}\" "
            f'-filter:v "crop={iup_region}" '
            f"\"{os.path.join(video+'_up', '%04d_img.png')}\""
            " > split_logs.txt 2>&1"
        )
        code = os.system(
            cmd
        )
        if code != 0:
            exit(code)
        code = os.system(
            f"ffmpeg -i \"{os.path.join(video, '%04d_img.png')}\" "
            f'-filter:v "crop={idw_region}" '
            f"\"{os.path.join(video+'_dw', '%04d_img.png')}\""
            " > split_logs.txt 2>&1"
        )
        if code != 0:
            exit(code)

        # crop mask images
        code = os.system(
            f"ffmpeg -i \"{os.path.join(video, '%04d')}{mask_suffix}.png\" "
            f'-filter:v "crop={iup_region}" '
            f"\"{os.path.join(video+'_up', '%04d')}{mask_suffix}.png\""
            " > split_logs.txt 2>&1"
        )
        if code != 0:
            exit(code)
        code = os.system(
            f"ffmpeg -i \"{os.path.join(video, '%04d')}{mask_suffix}.png\" "
            f'-filter:v "crop={idw_region}" '
            f"\"{os.path.join(video+'_dw', '%04d')}{mask_suffix}.png\""
            " > split_logs.txt 2>&1"
        )
        if code != 0:
            exit(code)

        print(f" Splitted {video} ({i+1}/{len(videos)})")


def fixed_merge(videos, factors, output_dir, suffix, outputs_list, overlap=0):
    print(f"Reconstructing {len(videos)} output images")
    for i, video in enumerate(videos):
        if i < (len(factors)) and factors[i]:
            # video split, merging
            out_path = os.path.join(output_dir, os.path.basename(video)).replace(
                "\\", "/"
            )

            try:
                os.makedirs(out_path + suffix)
            except FileExistsError:
                continue

            outpup = (out_path + "_up" + suffix).replace("\\", "/")
            outpdw = (out_path + "_dw" + suffix).replace("\\", "/")

            for o in outputs_list:
                code = os.system(
                    f"ffmpeg -i \"{outpup}/%04d_{o}.png\" -i \"{outpdw}/%04d_{o}.png\" "
                    f'-filter_complex "[0:0]crop=iw:ih-{overlap}:0:0[v0];'
                    f"[1:0]crop=iw:ih-{overlap}:0:{overlap}[v1];"
                    f'[v0][v1]vstack" '
                    f"\"{out_path + suffix}/%04d_{o}.png\" -hide_banner"
                    " > merge_logs.txt"
                )
                if code != 0:
                    exit(code)

            print(f" Merged {video} ({i+1}/{len(videos)})")

[((8, 19, 8, 56), 'os.path.join', 'os.path.join', ({(8, 32, 8, 47): 'background_path', (8, 49, 8, 55): 'f[:-4]'}, {}), '(background_path, f[:-4])', False, 'import os\n'), ((31, 15, 33, 9), 'os.system', 'os.system', ({(32, 12, 32, 15): 'cmd'}, {}), '(cmd)', False, 'import os\n'), ((67, 15, 69, 9), 'os.system', 'os.system', ({(68, 12, 68, 15): 'cmd'}, {}), '(cmd)', False, 'import os\n'), ((72, 15, 77, 9), 'os.system', 'os.system', ({(73, 12, 76, 36): 'f"""ffmpeg -y -i "{video + \'.png\'}" -filter:v "crop={idw_region}" "{video + \'_dw.png\'}" > split_logs.txt 2>&1"""'}, {}), '(\n    f\'ffmpeg -y -i "{video + \\\'.png\\\'}" -filter:v "crop={idw_region}" "{video + \\\'_dw.png\\\'}" > split_logs.txt 2>&1\'\n    )', False, 'import os\n'), ((89, 15, 91, 9), 'os.system', 'os.system', ({(90, 12, 90, 15): 'cmd'}, {}), '(cmd)', False, 'import os\n'), ((8, 66, 8, 93), 'os.listdir', 'os.listdir', ({(8, 77, 8, 92): 'background_path'}, {}), '(background_path)', False, 'import os\n'), ((16, 12, 16, 43), 'os.makedirs', 'os.makedirs', ({(16, 24, 16, 42): "(background + '_up')"}, {}), "(background + '_up')", False, 'import os\n'), ((17, 12, 17, 43), 'os.makedirs', 'os.makedirs', ({(17, 24, 17, 42): "(background + '_dw')"}, {}), "(background + '_dw')", False, 'import os\n'), ((51, 12, 51, 38), 'os.makedirs', 'os.makedirs', ({(51, 24, 51, 37): "(video + '_up')"}, {}), "(video + '_up')", False, 'import os\n'), ((52, 12, 52, 38), 'os.makedirs', 'os.makedirs', ({(52, 24, 52, 37): "(video + '_dw')"}, {}), "(video + '_dw')", False, 'import os\n'), ((26, 27, 26, 67), 'os.path.join', 'os.path.join', ({(26, 40, 26, 50): 'background', (26, 52, 26, 66): '"""%04d_img.png"""'}, {}), "(background, '%04d_img.png')", False, 'import os\n'), ((26, 13, 26, 59), 'os.path.join', 'os.path.join', ({(26, 26, 26, 42): "(background + '_up')", (26, 44, 26, 58): '"""%04d_img.png"""'}, {}), "(background + '_up', '%04d_img.png')", False, 'import os\n'), ((84, 27, 84, 62), 'os.path.join', 'os.path.join', ({(84, 40, 84, 45): 'video', (84, 47, 84, 61): '"""%04d_img.png"""'}, {}), "(video, '%04d_img.png')", False, 'import os\n'), ((84, 13, 84, 54), 'os.path.join', 'os.path.join', ({(84, 26, 84, 37): "(video + '_up')", (84, 39, 84, 53): '"""%04d_img.png"""'}, {}), "(video + '_up', '%04d_img.png')", False, 'import os\n'), ((134, 16, 134, 46), 'os.makedirs', 'os.makedirs', ({(134, 28, 134, 45): '(out_path + suffix)'}, {}), '(out_path + suffix)', False, 'import os\n'), ((142, 23, 149, 17), 'os.system', 'os.system', ({(143, 20, 148, 39): 'f"""ffmpeg -i "{outpup}/%04d_{o}.png" -i "{outpdw}/%04d_{o}.png" -filter_complex "[0:0]crop=iw:ih-{overlap}:0:0[v0];[1:0]crop=iw:ih-{overlap}:0:{overlap}[v1];[v0][v1]vstack" "{out_path + suffix}/%04d_{o}.png" -hide_banner > merge_logs.txt"""'}, {}), '(\n    f\'ffmpeg -i "{outpup}/%04d_{o}.png" -i "{outpdw}/%04d_{o}.png" -filter_complex "[0:0]crop=iw:ih-{overlap}:0:0[v0];[1:0]crop=iw:ih-{overlap}:0:{overlap}[v1];[v0][v1]vstack" "{out_path + suffix}/%04d_{o}.png" -hide_banner > merge_logs.txt\'\n    )', False, 'import os\n'), ((37, 27, 37, 67), 'os.path.join', 'os.path.join', ({(37, 40, 37, 50): 'background', (37, 52, 37, 66): '"""%04d_img.png"""'}, {}), "(background, '%04d_img.png')", False, 'import os\n'), ((37, 13, 37, 59), 'os.path.join', 'os.path.join', ({(37, 26, 37, 42): "background + '_dw'", (37, 44, 37, 58): '"""%04d_img.png"""'}, {}), "(background + '_dw', '%04d_img.png')", False, 'import os\n'), ((95, 27, 95, 62), 'os.path.join', 'os.path.join', ({(95, 40, 95, 45): 'video', (95, 47, 95, 61): '"""%04d_img.png"""'}, {}), "(video, '%04d_img.png')", False, 'import os\n'), ((95, 13, 95, 54), 'os.path.join', 'os.path.join', ({(95, 26, 95, 37): "video + '_dw'", (95, 39, 95, 53): '"""%04d_img.png"""'}, {}), "(video + '_dw', '%04d_img.png')", False, 'import os\n'), ((105, 27, 105, 54), 'os.path.join', 'os.path.join', ({(105, 40, 105, 45): 'video', (105, 47, 105, 53): '"""%04d"""'}, {}), "(video, '%04d')", False, 'import os\n'), ((105, 13, 105, 46), 'os.path.join', 'os.path.join', ({(105, 26, 105, 37): "video + '_up'", (105, 39, 105, 45): '"""%04d"""'}, {}), "(video + '_up', '%04d')", False, 'import os\n'), ((113, 27, 113, 54), 'os.path.join', 'os.path.join', ({(113, 40, 113, 45): 'video', (113, 47, 113, 53): '"""%04d"""'}, {}), "(video, '%04d')", False, 'import os\n'), ((113, 13, 113, 46), 'os.path.join', 'os.path.join', ({(113, 26, 113, 37): "video + '_dw'", (113, 39, 113, 45): '"""%04d"""'}, {}), "(video + '_dw', '%04d')", False, 'import os\n'), ((129, 48, 129, 71), 'os.path.basename', 'os.path.basename', ({(129, 65, 129, 70): 'video'}, {}), '(video)', False, 'import os\n')]