import argparse
import cv2
import math
import os


def compress_and_write_image(cv_image, output_path, max_size_kb=800):
    quality = 90
    while quality > 0:
        is_written = cv2.imwrite(output_path, cv_image, [cv2.IMWRITE_JPEG_QUALITY, quality])
        if not is_written:
            print(f"Failed to write the image {output_path}.")
            return False
        size_kb = os.path.getsize(output_path) / 1024
        if size_kb <= max_size_kb:
            print(f'Success: {output_path}')
            return True
        quality -= 5
    print(f"Could not compress the image to the desired size: {output_path}.")
    return False


def crop_and_compress_img(image_path: str):
    image = cv2.imread(image_path)
    h, w, c = image.shape
    w_half = math.floor(w/2)
    crop1 = image[0:h, 0:w_half]
    crop2 = image[0:h, w_half:w]

    splitted_filename = image_path.split('.')
    path_a = splitted_filename[0] + 'a.' + splitted_filename[1]
    path_b = splitted_filename[0] + 'b.' + splitted_filename[1]
    compress_and_write_image(crop1, path_a, 800)
    compress_and_write_image(crop2, path_b, 800)


def process_files(path):
    if not os.path.isdir(path):
        print(f"{path} is not a valid directory.")
        return

    for root, dirs, files in os.walk(path):
        for file in files:
            file_path = os.path.join(root, file)
            crop_and_compress_img(file_path)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Crop and compress all images in all subfolders of the given path")
    parser.add_argument("path", type=str, help="The path to the root-directory")
    args = parser.parse_args()
    directory_path = args.path
    process_files(directory_path)

