import os
from PIL import Image
import math

def generate_thumbs_from_zip(thumbnail_path, z) ->str:

    file_list = z.namelist()

    if not os.path.isfile(thumbnail_path):

        jpgs = []  # Stores.jpg files if another file with same name is found
        for file in file_list:
            if file.endswith('.jpg'):
                base_name = os.path.splitext(file)[0]  # Get basename no extension
                for other_file in file_list:
                    other_base_name = os.path.splitext(other_file)[0]
                    if file != other_file and base_name == other_base_name:
                        jpgs.append(file)
                        break
        if not jpgs:
            return ''

        # How many images do fit in a row/column?
        n = len(jpgs)
        grid_size = math.ceil(math.sqrt(n))

        # Exception for only 1 image
        if n == 1:
            thumbnail_size = (512, 512)
        else:
            thumbnail_size = (1024, 1024)

        # Calculate cell size for grid
        cell_width = thumbnail_size[0] // grid_size
        cell_height = thumbnail_size[1] // grid_size

        if n == 2:  # Exception for only 2 images (half vert size)
            thumbnail_size = (1024, 512)

        # Create a blank thumbnail
        thumbnail = Image.new('RGB', thumbnail_size)

        # Put images in grid
        for i, imgpath in enumerate(jpgs):
            row = i // grid_size
            col = i % grid_size
            position = (col * cell_width, row * cell_height)
            
            # Create a thumbnail with resized and organized images.
            # Adjust image size if needed, to fit in grid
            img = Image.open(z.open(imgpath))
#            img = img.convert("RGB")  # Convert to RGB just in case
            img.thumbnail((cell_width, cell_height))

            paste_position = (
                position[0] + (cell_width - img.width) // 2,
                position[1] + (cell_height - img.height) // 2
            )
            thumbnail.paste(img, paste_position)

        thumbnail.save(thumbnail_path)

    return thumbnail_path
