#!/usr/bin/env python3
"""Un contatto per gioco: tutte le foto dell'archivio, numerate, in un jpg solo.

Serve a scegliere le quattro foto del carosello senza aprirle una per una.

    .venv/bin/python provini.py "Blokus" "Gizmos"     alcuni giochi
    .venv/bin/python provini.py --tutti               tutti quelli con foto
"""
import os, re, sys, unicodedata
from PIL import Image, ImageDraw, ImageFont

QUI = os.path.dirname(os.path.abspath(__file__))
BASE = os.path.dirname(QUI)
ARCHIVIO = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "archivio")
OUT = os.path.join(BASE, "out", "prove", "foto")
FONT = os.path.join(BASE, "font", "Inter-Bold.ttf")
CELLA, COLONNE, MARGINE = 420, 4, 12


def norm(s):
    s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode().lower()
    return re.sub(r"[^a-z0-9]", "", s)


def foto_di(nome):
    """[(etichetta, percorso), ...] per un nome d'archivio, cercando nelle cartelle.

    Il confronto e' sul nome normalizzato, se no "Honshu" e "Honshu'" sembrano due
    giochi e il contatto ne mostra meta'.
    """
    cercato, out = norm(nome), []
    for cart in sorted(os.listdir(ARCHIVIO)):
        piena = os.path.join(ARCHIVIO, cart)
        if not os.path.isdir(piena):
            continue
        for f in sorted(os.listdir(piena)):
            m = re.match(r"^(.*) - (.+)\.(jpg|jpeg|png)$", f, re.I)
            if m and norm(m.group(1)) == cercato:
                out.append((m.group(2), os.path.join(piena, f)))
    return out


def contatto(nome):
    foto = foto_di(nome)
    if not foto:
        print(f"  {nome}: nessuna foto"); return None
    righe = (len(foto) + COLONNE - 1) // COLONNE
    L = COLONNE * (CELLA + MARGINE) + MARGINE
    A = righe * (CELLA + MARGINE + 34) + MARGINE
    tela = Image.new("RGB", (L, A), "#111111")
    d = ImageDraw.Draw(tela)
    try:
        f = ImageFont.truetype(FONT, 26)
    except OSError:
        f = ImageFont.load_default()
    for i, (etichetta, percorso) in enumerate(foto):
        im = Image.open(percorso)
        im.thumbnail((CELLA, CELLA))
        x = MARGINE + (i % COLONNE) * (CELLA + MARGINE)
        y = MARGINE + (i // COLONNE) * (CELLA + MARGINE + 34)
        tela.paste(im, (x + (CELLA - im.width) // 2, y + (CELLA - im.height) // 2))
        d.text((x + 4, y + CELLA + 4), etichetta, font=f, fill="#f0b429")
    os.makedirs(OUT, exist_ok=True)
    dest = os.path.join(OUT, nome + ".jpg")
    tela.save(dest, quality=82)
    print(f"  {nome}: {len(foto)} foto -> {os.path.basename(dest)}")
    return dest


if __name__ == "__main__":
    if sys.argv[1:2] == ["--tutti"]:
        nomi = sorted({m.group(1) for c in os.listdir(ARCHIVIO)
                       if os.path.isdir(os.path.join(ARCHIVIO, c))
                       for f in os.listdir(os.path.join(ARCHIVIO, c))
                       if (m := re.match(r"^(.*) - (.+)\.(jpg|jpeg|png)$", f, re.I))})
    else:
        nomi = sys.argv[1:]
    for n in nomi:
        contatto(n)
