from PIL import Image
import os
import sys
import subprocess

def resize_and_compress_image(input_path, output_path, max_size=1000, target_size_kb=100, max_quality=85):
    try:
        with Image.open(input_path) as img:
            img = img.convert("RGB")  # Convert to 24-bit RGB

            width, height = img.size

            # Resize if needed
            if width > max_size or height > max_size:
                if width > height:
                    ratio = max_size / float(width)
                    new_height = int((float(height) * float(ratio)))
                    img = img.resize((max_size, new_height), Image.LANCZOS)
                else:
                    ratio = max_size / float(height)
                    new_width = int((float(width) * float(ratio)))
                    img = img.resize((new_width, max_size), Image.LANCZOS)

            # Remove metadata
            data = list(img.getdata())
            img_without_metadata = Image.new(img.mode, img.size)
            img_without_metadata.putdata(data)

            # Attempt to save with different compression levels
            temp_webp_output_path = output_path + ".webp"
            for quality in range(max_quality, 0, -5):
                img_without_metadata.save(temp_webp_output_path, "WEBP", quality=quality)
                if os.path.getsize(temp_webp_output_path) <= target_size_kb * 1024:
                    break

            print(f"Resized and compressed image saved to {temp_webp_output_path} with quality {quality}")

            # Change the ownership to root:root
            subprocess.run(["sudo", "chown", "root:root", temp_webp_output_path], check=True)
            print(f"Ownership changed to root:root for {temp_webp_output_path}")

            # Remove the original file
            os.remove(input_path)
            print(f"Original image {input_path} removed")

            # Rename the WebP file to replace the original
            final_webp_output_path = os.path.splitext(input_path)[0] + ".webp"
            os.rename(temp_webp_output_path, final_webp_output_path)
            print(f"Renamed {temp_webp_output_path} to {final_webp_output_path}")

    except Exception as e:
        print(f"Error resizing and compressing image {input_path}: {e}")

def resize_images_in_folder(folder_path):
    try:
        for filename in os.listdir(folder_path):
            if filename.lower().endswith(('png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp')):
                input_path = os.path.join(folder_path, filename)
                resize_and_compress_image(input_path, input_path)
    except Exception as e:
        print(f"Error processing folder {folder_path}: {e}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python resize_images.py <input_folder>")
        sys.exit(1)

    input_folder = sys.argv[1]

    if not os.path.exists(input_folder):
        print(f"Error: Input folder {input_folder} does not exist")
        sys.exit(1)

    if not os.access(input_folder, os.R_OK):
        print(f"Error: Input folder {input_folder} is not readable")
        sys.exit(1)

    if not os.access(input_folder, os.W_OK):
        print(f"Error: Input folder {input_folder} is not writable")
        sys.exit(1)

    resize_images_in_folder(input_folder)
