# Hoja de contacto comparada de 4 packs Pawchive (WaifuInvoker) + Purah.
# Lee Archivos/PAWCHISE/*/*.png (orden numérico) y genera una hoja por pack
# y una combinada de miniaturas.

import pathlib
import re
from PIL import Image, ImageDraw, ImageFont

BASE = pathlib.Path(r"C:\Users\Usuario\Downloads\SD")
SRC = BASE / "Archivos" / "PAWCHISE"
OUT = BASE / "Output"

def nkey(p: pathlib.Path):
    m = re.search(r"(\d+)", p.stem)
    return int(m.group(1)) if m else 9999

def build_sheet(items, cols=6, thumb_w=300, label_h=26, pad=6):
    thumbs = []
    for label, p in items:
        im = Image.open(p).convert("RGB")
        r = thumb_w / im.width
        thumbs.append((label, im.resize((thumb_w, int(im.height * r))), p.name))
    rows = (len(thumbs) + cols - 1) // cols
    cell_h = max(t[1].height for t in thumbs) + label_h + pad * 2
    W = cols * (thumb_w + pad) + pad
    H = rows * cell_h + pad
    sheet = Image.new("RGB", (W, H), (18, 18, 18))
    d = ImageDraw.Draw(sheet)
    try:
        font = ImageFont.load_default(size=13)
    except TypeError:
        font = ImageFont.load_default()
    for i, (label, th, name) in enumerate(thumbs):
        x = pad + (i % cols) * (thumb_w + pad)
        y = pad + (i // cols) * cell_h
        sheet.paste(th, (x, y + label_h))
        d.text((x + 2, y + 4), f"{label} {name}", fill=(255, 210, 120), font=font)
    return sheet

all_items = []
for d in sorted(SRC.iterdir()):
    if not d.is_dir():
        continue
    files = sorted(d.rglob("*.png"), key=nkey)
    items = [(d.name.split()[0], f) for f in files]
    sheet = build_sheet(items, cols=6, thumb_w=300)
    out = OUT / f"pawchive_sheet_{d.name.split()[0].lower()}.jpg"
    sheet.save(out, quality=88)
    print(out, sheet.size, len(items))
    all_items.extend(items)

# Purah ya descargado antes
purah = BASE / "Output" / "pawchive_refs" / "WaifuInvoker_Purah_Zelda"
if purah.exists():
    files = sorted(purah.glob("*.png"), key=nkey)
    all_items.extend([("Purah", f) for f in files])

combined = build_sheet(all_items, cols=8, thumb_w=230)
out = OUT / "pawchive_all_sheet.jpg"
combined.save(out, quality=85)
print(out, combined.size, len(all_items))
