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)})")

[((157, 194), 'os.path.join', 'os.path.join', (['background_path', 'f[:-4]'], {}), '(background_path, f[:-4])\n', (169, 194), False, 'import os\n'), ((1089, 1103), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (1098, 1103), False, 'import os\n'), ((2253, 2267), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2262, 2267), False, 'import os\n'), ((2350, 2483), 'os.system', 'os.system', (['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    )\n', (2359, 2483), False, 'import os\n'), ((2867, 2881), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2876, 2881), False, 'import os\n'), ((204, 231), 'os.listdir', 'os.listdir', (['background_path'], {}), '(background_path)\n', (214, 231), False, 'import os\n'), ((508, 539), 'os.makedirs', 'os.makedirs', (["(background + '_up')"], {}), "(background + '_up')\n", (519, 539), False, 'import os\n'), ((552, 583), 'os.makedirs', 'os.makedirs', (["(background + '_dw')"], {}), "(background + '_dw')\n", (563, 583), False, 'import os\n'), ((1707, 1733), 'os.makedirs', 'os.makedirs', (["(video + '_up')"], {}), "(video + '_up')\n", (1718, 1733), False, 'import os\n'), ((1746, 1772), 'os.makedirs', 'os.makedirs', (["(video + '_dw')"], {}), "(video + '_dw')\n", (1757, 1772), False, 'import os\n'), ((856, 896), 'os.path.join', 'os.path.join', (['background', '"""%04d_img.png"""'], {}), "(background, '%04d_img.png')\n", (868, 896), False, 'import os\n'), ((842, 890), 'os.path.join', 'os.path.join', (["(background + '_up')", '"""%04d_img.png"""'], {}), "(background + '_up', '%04d_img.png')\n", (854, 890), False, 'import os\n'), ((2655, 2690), 'os.path.join', 'os.path.join', (['video', '"""%04d_img.png"""'], {}), "(video, '%04d_img.png')\n", (2667, 2690), False, 'import os\n'), ((2641, 2684), 'os.path.join', 'os.path.join', (["(video + '_up')", '"""%04d_img.png"""'], {}), "(video + '_up', '%04d_img.png')\n", (2653, 2684), False, 'import os\n'), ((4371, 4401), 'os.makedirs', 'os.makedirs', (['(out_path + suffix)'], {}), '(out_path + suffix)\n', (4382, 4401), False, 'import os\n'), ((4659, 4917), 'os.system', 'os.system', (['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    )\n', (4668, 4917), False, 'import os\n'), ((1224, 1264), 'os.path.join', 'os.path.join', (['background', '"""%04d_img.png"""'], {}), "(background, '%04d_img.png')\n", (1236, 1264), False, 'import os\n'), ((1210, 1258), 'os.path.join', 'os.path.join', (["(background + '_dw')", '"""%04d_img.png"""'], {}), "(background + '_dw', '%04d_img.png')\n", (1222, 1258), False, 'import os\n'), ((3002, 3037), 'os.path.join', 'os.path.join', (['video', '"""%04d_img.png"""'], {}), "(video, '%04d_img.png')\n", (3014, 3037), False, 'import os\n'), ((2988, 3031), 'os.path.join', 'os.path.join', (["(video + '_dw')", '"""%04d_img.png"""'], {}), "(video + '_dw', '%04d_img.png')\n", (3000, 3031), False, 'import os\n'), ((3325, 3352), 'os.path.join', 'os.path.join', (['video', '"""%04d"""'], {}), "(video, '%04d')\n", (3337, 3352), False, 'import os\n'), ((3311, 3346), 'os.path.join', 'os.path.join', (["(video + '_up')", '"""%04d"""'], {}), "(video + '_up', '%04d')\n", (3323, 3346), False, 'import os\n'), ((3638, 3665), 'os.path.join', 'os.path.join', (['video', '"""%04d"""'], {}), "(video, '%04d')\n", (3650, 3665), False, 'import os\n'), ((3624, 3659), 'os.path.join', 'os.path.join', (["(video + '_dw')", '"""%04d"""'], {}), "(video + '_dw', '%04d')\n", (3636, 3659), False, 'import os\n'), ((4263, 4286), 'os.path.basename', 'os.path.basename', (['video'], {}), '(video)\n', (4279, 4286), False, 'import os\n')]