import os

# Configuration
input_file = "cointextures.txt"
images_per_atlas = 16  # 4x4 grid
tile_layout = "4x4"

diffuse_files = []
normal_files = []

# 1. Parse the text file and sort into categories
with open(input_file, "r") as f:
    for line in f:
        # Strip line numbers and whitespace
        filename = line.strip().split()[-1] if line.strip() else ""
        if not filename:
            continue

        if "_normal.webp" in filename:
            normal_files.append(filename)
        else:
            diffuse_files.append(filename)

# 2. Helper function to chunk lists into sets of 16
def chunk_list(lst, size):
    return [lst[i:i + size] for i in range(0, len(lst), size)]

diffuse_chunks = chunk_list(diffuse_files, images_per_atlas)
normal_chunks = chunk_list(normal_files, images_per_atlas)

# 3. Generate ImageMagick commands
print("# --- IMAGEMAGICK BASH COMMANDS --- \n")

print("# Diffuse Atlases")
for idx, chunk in enumerate(diffuse_chunks):
    # Ensure missing slots in a partial final grid are padded transparently
    padding = f"-background transparent -extent 4096x4096" if len(chunk) < images_per_atlas else ""
    files_str = " ".join(chunk)
    print(f"montage {files_str} -geometry 1024x1024+0+0 -tile {tile_layout} diffuse_atlas_{idx}.webp")

print("\n# Normal Map Atlases")
for idx, chunk in enumerate(normal_chunks):
    # Pad normal map background with neutral normal color (#8080ff) instead of transparency
    padding = f"-background '#8080ff' -extent 4096x4096" if len(chunk) < images_per_atlas else ""
    files_str = " ".join(chunk)
    print(f"montage {files_str} -geometry 1024x1024+0+0 -tile {tile_layout} normal_atlas_{idx}.webp")
