#!/usr/bin/env python3
# Сборка контактных листов по каждому проекту (сетка 4x3 с номерами) для vision-проверки
import os, re
from PIL import Image, ImageDraw

WORK = "/root/site/video/site_renders"
OUT = "/root/site/video/verify_sheets2"
os.makedirs(OUT, exist_ok=True)

CELL_W, CELL_H = 320, 240
COLS, ROWS = 4, 3

def make_sheet(proj, files):
    imgs = []
    for f in files:
        try:
            im = Image.open(os.path.join(WORK, proj, f)).convert("RGB")
            im.thumbnail((CELL_W - 8, CELL_H - 24), Image.LANCZOS)
            imgs.append((f, im))
        except Exception as e:
            print("skip", proj, f, e)
    n = len(imgs)
    if n == 0:
        return None
    cols = min(COLS, max(1, (n + ROWS - 1) // ROWS if n > ROWS else n))
    # простая сетка: не более COLS колонок
    cols = min(cols, COLS)
    rows = (n + cols - 1) // cols
    sheet = Image.new("RGB", (cols * CELL_W, rows * CELL_H), "white")
    d = ImageDraw.Draw(sheet)
    for i, (fname, im) in enumerate(imgs):
        x = (i % cols) * CELL_W
        y = (i // cols) * CELL_H
        sheet.paste(im, (x + 4, y + 4))
        d.rectangle([x, y + CELL_H - 18, x + CELL_W - 1, y + CELL_H - 1], fill="black")
        d.text((x + 6, y + CELL_H - 15), f"{i+1}", fill="white")
    path = os.path.join(OUT, proj.replace(" ", "_").replace("+", "p") + ".jpg")
    sheet.save(path, quality=88)
    return path

total = 0
for proj in sorted(os.listdir(WORK)):
    pdir = os.path.join(WORK, proj)
    if not os.path.isdir(pdir):
        continue
    files = sorted(os.listdir(pdir))
    if not files:
        print(f"!!! {proj}: ПУСТО")
        continue
    p = make_sheet(proj, files)
    if p:
        total += 1
        print(f"{proj}: {len(files)} файлов -> {os.path.basename(p)}")
print("Листов собрано:", total)
