#!/usr/bin/env python3
"""Assemble the coloring book PDF ready for Amazon KDP."""

from PIL import Image, ImageDraw, ImageFont
import os

W, H = 2550, 3300  # 8.5x11" at 300 DPI
OUT_DIR = "/home/node/.openclaw/workspace/books/mondo-dei-dinosauri"
IMG_DIR = os.path.join(OUT_DIR, "images")
PDF_PATH = os.path.join(OUT_DIR, "Il-Mondo-dei-Dinosauri-Libro-da-Colorare.pdf")

# Try to load a font; fallback to default
FONT_SIZE_TITLE = 120
FONT_SIZE_SUBTITLE = 60
FONT_SIZE_BODY = 48
FONT_SIZE_DEDIC = 70

fonts = {}
for size, name in [(120, "title"), (60, "subtitle"), (48, "body"), (70, "dedic"), (80, "cover")]:
    try:
        fonts[size] = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", size)
    except:
        try:
            fonts[size] = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", size)
        except:
            fonts[size] = ImageFont.load_default()

def new_page():
    img = Image.new("RGB", (W, H), "white")
    draw = ImageDraw.Draw(img)
    return img, draw

def draw_centered_text(draw, text, y, font_key, max_width=W-400):
    """Draw centered text, wrapping if needed."""
    font = fonts.get(font_key, fonts[list(fonts.keys())[0]])
    lines = []
    for word in text.split():
        if not lines:
            lines.append(word)
        else:
            test = lines[-1] + " " + word
            bb = draw.textbbox((0, 0), test, font=font)
            if bb[2] - bb[0] <= max_width:
                lines[-1] = test
            else:
                lines.append(word)
    
    total_h = sum(draw.textbbox((0, 0), l, font=font)[3] - draw.textbbox((0, 0), l, font=font)[1] for l in lines) + 10 * (len(lines)-1)
    start_y = y - total_h // 2
    
    for line in lines:
        bb = draw.textbbox((0, 0), line, font=font)
        lw = bb[2] - bb[0]
        lh = bb[3] - bb[1]
        draw.text(((W - lw) // 2, start_y), line, fill="black", font=font)
        start_y += lh + 10

def draw_multiline_text(draw, text, y, font_key, max_width=W-400, line_spacing=15):
    """Draw wrapped text from left."""
    font = fonts.get(font_key, fonts[list(fonts.keys())[0]])
    lines = []
    for word in text.split():
        if not lines:
            lines.append(word)
        else:
            test = lines[-1] + " " + word
            bb = draw.textbbox((0, 0), test, font=font)
            if bb[2] - bb[0] <= max_width:
                lines[-1] = test
            else:
                lines.append(word)
    
    start_y = y
    for line in lines:
        bb = draw.textbbox((0, 0), line, font=font)
        lh = bb[3] - bb[1]
        draw.text((200, start_y), line, fill="black", font=font)
        start_y += lh + line_spacing
    return start_y

# ─── PAGE 1: COVER ──────────────────────────────────────────
img, d = new_page()
# Decorative border
d.rectangle([50, 50, W-50, H-50], outline="black", width=20)
d.rectangle([80, 80, W-80, H-80], outline="black", width=8)

# Title
draw_centered_text(d, "IL MONDO DEI", 600, 80)
draw_centered_text(d, "DINOSAURI", 780, 120)

# Subtitle
draw_centered_text(d, "Libro da Colorare per Bambini", 950, 60)

# Decorative line
d.line([600, 1050, W-600, 1050], fill="black", width=12)

# More text
draw_centered_text(d, "20 Fantastici Dinosauri da Scoprire e Colorare", 1150, 48)
draw_centered_text(d, "T-Rex  ·  Triceratopo  ·  Stegosauro  ·  Brachiosauro", 1280, 40)
draw_centered_text(d, "e tanti altri amici preistorici!", 1380, 40)

# Age range
d.rectangle([W//2-300, 1500, W//2+300, 1680], outline="black", width=12)
draw_centered_text(d, "Età 4-8 Anni", 1590, 70)

# Bottom info
d.line([600, 1900, W-600, 1900], fill="black", width=6)
draw_centered_text(d, "Formato 8.5\" × 11\"  ·  20 Illustrazioni a Pagina Singola", 2050, 40)
draw_centered_text(d, "Stimola la Creatività e la Motricità Fine", 2150, 40)
draw_centered_text(d, "Divertimento Preistorico Garantito!", 2250, 40)

cover = img.copy()
img.save(os.path.join(OUT_DIR, "cover.png"), "PNG", dpi=(300, 300))
print("✅ Copertina creata")

# ─── PAGE 2: DEDICA ─────────────────────────────────────────
img, d = new_page()
d.rectangle([100, 100, W-100, H-100], outline="black", width=8)

# Decorative small dinos
d.ellipse([150, 200, 300, 350], outline="black", width=8)
d.ellipse([250, 250, 350, 350], outline="black", width=8)
d.ellipse([W-350, 200, W-150, 350], outline="black", width=8)
d.ellipse([W-350, 250, W-250, 350], outline="black", width=8)

draw_centered_text(d, "A te, piccolo esploratore!", 900, 70)
draw_centered_text(d, "✦", 1050, 48)

ded_text = "Questo libro è tuo! Prendi i tuoi colori preferiti e preparati a viaggiare nel tempo, in un mondo lontano lontano dove i dinosauri regnavano sovrani."
draw_multiline_text(d, ded_text, 1200, 60, max_width=W-500, line_spacing=20)

draw_centered_text(d, "Ogni pagina è un'avventura che aspetta solo te.", 1600, 60)
draw_centered_text(d, "Divertiti!", 1900, 80)

d.ellipse([W//2-30, 2100, W//2+30, 2160], fill="black")
d.ellipse([W//2-15, 2120, W//2+15, 2170], fill="black")
d.line([W//2, 2160, W//2, 2240], fill="black", width=8)
d.ellipse([W//2-40, 2220, W//2+40, 2280], outline="black", width=6)
d.ellipse([W//2-35, 2225, W//2+35, 2275], outline="black", width=6)

print("✅ Pagina dedica creata")

# ─── PAGE 3: INTRODUZIONE PER GENITORI ──────────────────────
img, d = new_page()
d.rectangle([100, 100, W-100, H-100], outline="black", width=8)

draw_centered_text(d, "PER I GENITORI", 350, 80)
d.line([600, 450, W-600, 450], fill="black", width=6)

intro_text = (
    "Caro genitore,\n\n"
    "Questo libro da colorare è molto più di un semplice passatempo. "
    "Colorare aiuta i bambini a sviluppare la concentrazione, la coordinazione "
    "occhio-mano e le capacità motorie fini, preparandoli gradualmente "
    "alla scrittura.\n\n"
    "I dinosauri, con il loro fascino senza tempo, stimolano la curiosità "
    "e l'immaginazione, trasformando ogni pagina in un'opportunità di "
    "apprendimento.\n\n"
    "Regala al tuo bambino momenti di tranquillità e creatività lontano "
    "dagli schermi: non c'è regalo più prezioso.\n\n"
    "Buon divertimento preistorico!"
)
draw_multiline_text(d, intro_text, 550, 50, max_width=W-500, line_spacing=15)

print("✅ Pagina introduzione creata")

# ─── PAGES 4-23: ILLUSTRATIONS ───────────────────────────────
image_paths = sorted([os.path.join(IMG_DIR, f) for f in os.listdir(IMG_DIR) if f.endswith(".png")])

pages = [cover]
dedica = None  # We'll add dedica after creating it
intro = None

# Recreate dedica page for pages list
img, d = new_page()
d.rectangle([100, 100, W-100, H-100], outline="black", width=8)
d.ellipse([150, 200, 300, 350], outline="black", width=8)
d.ellipse([250, 250, 350, 350], outline="black", width=8)
d.ellipse([W-350, 200, W-150, 350], outline="black", width=8)
d.ellipse([W-350, 250, W-250, 350], outline="black", width=8)
draw_centered_text(d, "A te, piccolo esploratore!", 900, 70)
draw_centered_text(d, "✦", 1050, 48)
ded_text = "Questo libro è tuo! Prendi i tuoi colori preferiti e preparati a viaggiare nel tempo, in un mondo lontano lontano dove i dinosauri regnavano sovrani."
draw_multiline_text(d, ded_text, 1200, 60, max_width=W-500, line_spacing=20)
draw_centered_text(d, "Ogni pagina è un'avventura che aspetta solo te.", 1600, 60)
draw_centered_text(d, "Divertiti!", 1900, 80)
d.ellipse([W//2-30, 2100, W//2+30, 2160], fill="black")
d.ellipse([W//2-15, 2120, W//2+15, 2170], fill="black")
d.line([W//2, 2160, W//2, 2240], fill="black", width=8)
d.ellipse([W//2-40, 2220, W//2+40, 2280], outline="black", width=6)
d.ellipse([W//2-35, 2225, W//2+35, 2275], outline="black", width=6)
dedica = img.copy()

# Recreate intro page
img, d = new_page()
d.rectangle([100, 100, W-100, H-100], outline="black", width=8)
draw_centered_text(d, "PER I GENITORI", 350, 80)
d.line([600, 450, W-600, 450], fill="black", width=6)
intro_text = (
    "Caro genitore,\n\n"
    "Questo libro da colorare è molto più di un semplice passatempo. "
    "Colorare aiuta i bambini a sviluppare la concentrazione, la coordinazione "
    "occhio-mano e le capacità motorie fini, preparandoli gradualmente "
    "alla scrittura.\n\n"
    "I dinosauri, con il loro fascino senza tempo, stimolano la curiosità "
    "e l'immaginazione, trasformando ogni pagina in un'opportunità di "
    "apprendimento.\n\n"
    "Regala al tuo bambino momenti di tranquillità e creatività lontano "
    "dagli schermi: non c'è regalo più prezioso.\n\n"
    "Buon divertimento preistorico!"
)
draw_multiline_text(d, intro_text, 550, 50, max_width=W-500, line_spacing=15)
intro = img.copy()

pages.append(dedica)
pages.append(intro)

# Dinosaur names for each page
dino_names = [
    "Tyrannosaurus Rex",
    "Triceratopo",
    "Stegosauro",
    "Brachiosauro",
    "Velociraptor",
    "Pterodattilo",
    "Diplodoco",
    "Anchilosauro",
    "Pteranodonte",
    "Spinosauro",
    "Parasaurolofo",
    "Pachycephalosauro",
    "Allosauro",
    "Iguanodonte",
    "Compsognato",
    "Dilofosauro",
    "Ankylosauro",
    "Triceratopo (mamma e cucciolo)",
    "T-Rex cucciolo",
    "Il Parco dei Dinosauri"
]

for i, img_path in enumerate(image_paths):
    dino_img = Image.open(img_path).convert("RGB")
    dino_img = dino_img.resize((W, H), Image.LANCZOS)
    
    # Add thin border
    d = ImageDraw.Draw(dino_img)
    d.rectangle([10, 10, W-10, H-10], outline="black", width=6)
    
    # Add page number at bottom
    page_num = i + 1
    num_text = f"{page_num}  /  20"
    bb = d.textbbox((0, 0), num_text, font=fonts.get(40, fonts[list(fonts.keys())[0]]))
    tw = bb[2] - bb[0]
    d.text((W - tw - 100, H - 80), num_text, fill="black", font=fonts.get(40, fonts[list(fonts.keys())[0]]))
    
    # Add dinosaur name at top
    name = dino_names[i] if i < len(dino_names) else f"Dinosauro {i+1}"
    bb = d.textbbox((0, 0), name, font=fonts.get(36, fonts[list(fonts.keys())[0]]))
    nw = bb[2] - bb[0]
    d.text(((W - nw) // 2, 60), name, fill="black", font=fonts.get(36, fonts[list(fonts.keys())[0]]))
    
    pages.append(dino_img)
    print(f"  ✓ Pagina {i+1}: {name}")

# ─── LAST PAGE: CTA ──────────────────────────────────────────
img, d = new_page()
d.rectangle([100, 100, W-100, H-100], outline="black", width=8)

draw_centered_text(d, "Grazie per aver viaggiato", 500, 70)
draw_centered_text(d, "con noi nel Mondo dei Dinosauri!", 650, 70)

draw_centered_text(d, "✦", 850, 48)

cta_text = (
    "Speriamo che tu e il tuo piccolo artista vi siate divertiti "
    "tantissimo a colorare questi fantastici dinosauri preistorici."
)
draw_multiline_text(d, cta_text, 1000, 55, max_width=W-500, line_spacing=20)

draw_centered_text(d, "Se questo libro ti è piaciuto,", 1300, 55)
draw_centered_text(d, "ci aiuteresti tantissimo lasciando", 1420, 55)
draw_centered_text(d, "una recensione su Amazon?", 1540, 55)

d.line([600, 1700, W-600, 1700], fill="black", width=6)

draw_centered_text(d, "Quale dinosauro hai colorato meglio?", 1900, 60)
draw_centered_text(d, "Raccontacelo con una recensione!", 2050, 60)

draw_centered_text(d, "🦕✨", 2250, 70)

draw_centered_text(d, "Grazie di cuore — Il team editoriale", 2450, 40)

pages.append(img)
print("✅ Pagina CTA creata")

# ─── SAVE PDF ────────────────────────────────────────────────
print(f"\n📄 Salvando PDF con {len(pages)} pagine...")
pages[0].save(
    PDF_PATH,
    "PDF",
    save_all=True,
    append_images=pages[1:],
    dpi=(300, 300),
    title="Il Mondo dei Dinosauri — Libro da Colorare per Bambini",
    author="Il Mondo dei Dinosauri"
)

file_size = os.path.getsize(PDF_PATH)
print(f"\n✅ PDF creato con successo!")
print(f"  📁 Percorso: {PDF_PATH}")
print(f"  📄 Pagine: {len(pages)}")
print(f"  💾 Dimensione: {file_size / (1024*1024):.1f} MB")
print(f"  📐 Formato: 8.5x11\" a 300 DPI")
