import os, glob
from PIL import Image, ImageDraw, ImageFont

out = r"C:\Users\User\Documents\dev\coordenadas-content-system\Brands\FrenzySalon\05_projects\frenzy-website-redesign\assets\photos\_candidates"
files = sorted(glob.glob(os.path.join(out, "*.jpg")))
files = [f for f in files if "sheet" not in os.path.basename(f).lower()]

try:
    font = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", 18)
except Exception:
    font = ImageFont.load_default()

COLS, ROWS = 4, 3
CELL_W, CELL_H = 360, 400
LABEL_H = 26
PER = COLS * ROWS
sheet_w = COLS * CELL_W
sheet_h = ROWS * CELL_H

for si in range(0, len(files), PER):
    chunk = files[si:si + PER]
    canvas = Image.new("RGB", (sheet_w, sheet_h), (245, 245, 245))
    draw = ImageDraw.Draw(canvas)
    for i, fp in enumerate(chunk):
        r, c = divmod(i, COLS)
        ox, oy = c * CELL_W, r * CELL_H
        try:
            im = Image.open(fp).convert("RGB")
        except Exception:
            continue
        im.thumbnail((CELL_W - 16, CELL_H - LABEL_H - 16))
        px = ox + (CELL_W - im.width) // 2
        py = oy + 8 + (CELL_H - LABEL_H - 16 - im.height) // 2
        canvas.paste(im, (px, py))
        draw.rectangle([ox, oy, ox + CELL_W - 1, oy + CELL_H - 1], outline=(200, 200, 200))
        draw.text((ox + 8, oy + CELL_H - LABEL_H + 2), os.path.basename(fp)[:-4], fill=(20, 20, 20), font=font)
    n = si // PER + 1
    outp = os.path.join(out, f"_sheet-{n}.jpg")
    canvas.save(outp, quality=82)
    print("sheet", n, len(chunk), "->", outp)
print("total files", len(files))
