import os
import imageio.v3 as iio
from PIL import Image

input_dir = os.getcwd()
output_dir = os.path.join(input_dir, "output_images")
os.makedirs(output_dir, exist_ok=True)

supported_extensions = {
    ".avif", ".webp", ".png", ".heif", ".heic",
    ".bmp", ".tiff"
}

files = [
    f for f in os.listdir(input_dir)
    if os.path.splitext(f)[1].lower() in supported_extensions
]

total = len(files)
count = 0

print(f"Found {total} convertible images\n")

for filename in files:
    filepath = os.path.join(input_dir, filename)
    name, ext = os.path.splitext(filename)
    ext = ext.lower()

    count += 1

    try:
        if ext == ".avif":
            img_array = iio.imread(filepath)
            img = Image.fromarray(img_array).convert("RGB")
        else:
            img = Image.open(filepath).convert("RGB")

        output_path = os.path.join(output_dir, name + ".jpg")

        if os.path.exists(output_path):
            print(f"[{count}/{total}] ⏭️ Skipped (exists): {name}.jpg")
            continue

        img.thumbnail((320, 320))

        img.save(output_path, "JPEG", quality=90, subsampling=0)

        print(f"[{count}/{total}] ✅ Converted: {filename} → {name}.jpg")

    except Exception as e:
        print(f"[{count}/{total}] ❌ Failed: {filename} ({e})")

print("\nConversion finished.")