#!/usr/bin/env python3
"""Build the coloring book PDF for Animali da Compagnia."""

import os
from PIL import Image
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch, mm
from reportlab.lib.colors import HexColor, white, black
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader

# ── Paths ──────────────────────────────────────────────────────────────────
BOOK_DIR = "/home/node/.openclaw/workspace/books/animali-da-compagnia"
IMAGES_DIR = os.path.join(BOOK_DIR, "images")
OUTPUT_PDF = os.path.join(BOOK_DIR, "animali-da-compagnia.pdf")

# 8.5 x 11 inches at 300 DPI
PAGE_W, PAGE_H = letter  # 612 x 792 points (72 DPI base)
DPI = 300

# ── Colors ──────────────────────────────────────────────────────────────────
BG_COVER = HexColor("#FFE4E1")     # rosa caldo
BG_DEDICA = HexColor("#FFF8DC")    # crema
BG_INTRO = HexColor("#F0F8FF")     # azzurro chiarissimo
BG_ILLUSTRATION = white
BG_CTA = HexColor("#FFE4E1")       # rosa caldo
ACCENT = HexColor("#E6735E")       # corallo
DARK = HexColor("#2D2D2D")
GREY = HexColor("#666666")

# ── Helpers ─────────────────────────────────────────────────────────────────

def draw_page_bg(c, color):
    c.setFillColor(color)
    c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)

def draw_centered_text(c, text, y, font="Helvetica", size=18, color=DARK, max_width=None):
    c.setFillColor(color)
    c.setFont(font, size)
    if max_width:
        # simple word-wrap logic for long text
        words = text.split()
        lines = []
        current = ""
        for w in words:
            test = current + " " + w if current else w
            if c.stringWidth(test, font, size) < max_width:
                current = test
            else:
                if current:
                    lines.append(current)
                current = w
        if current:
            lines.append(current)
        for i, line in enumerate(lines):
            tw = c.stringWidth(line, font, size)
            c.drawString((PAGE_W - tw) / 2, y - i * (size * 1.3), line)
        return y - len(lines) * (size * 1.3)
    else:
        tw = c.stringWidth(text, font, size)
        c.drawString((PAGE_W - tw) / 2, y, text)
        return y

def draw_wrapped_text(c, text, x, y, font="Helvetica", size=14, color=DARK, leading=None, max_width=500):
    """Draw wrapped text and return bottom y."""
    c.setFillColor(color)
    c.setFont(font, size)
    leading = leading or size * 1.4
    words = text.split()
    lines = []
    current = ""
    for w in words:
        test = current + " " + w if current else w
        if c.stringWidth(test, font, size) < max_width:
            current = test
        else:
            if current:
                lines.append(current)
            current = w
    if current:
        lines.append(current)
    for i, line in enumerate(lines):
        c.drawString(x, y - i * leading, line)
    return y - len(lines) * leading

def add_page_number(c, page_num, total):
    c.setFont("Helvetica", 9)
    c.setFillColor(GREY)
    text = f"{page_num} / {total}"
    tw = c.stringWidth(text, "Helvetica", 9)
    c.drawString(PAGE_W - tw - 30, 20, text)

def add_image_centered_fit(c, img_path, margin=36):
    """Place image centered, fitting within page margins, maintaining aspect ratio."""
    img = Image.open(img_path)
    img_w, img_h = img.size
    
    max_w = PAGE_W - 2 * margin
    max_h = PAGE_H - 2 * margin - 60  # leave room for title text
    
    ratio = min(max_w / img_w, max_h / img_h)
    display_w = img_w * ratio
    display_h = img_h * ratio
    
    x = (PAGE_W - display_w) / 2
    y = (PAGE_H - display_h) / 2 - 20
    
    c.drawImage(ImageReader(img), x, y, width=display_w, height=display_h, preserveAspectRatio=True)

# ── Build PDF ──────────────────────────────────────────────────────────────

c = canvas.Canvas(OUTPUT_PDF, pagesize=letter)
c.setTitle("Animali da Compagnia - Libro da Colorare per Bambini")
c.setAuthor("Coloring Books for Kids")
c.setSubject("Libro da Colorare")
TOTAL_PAGES = 9  # cover + dedica + intro + 5 illustrations + CTA
page_num = 0

# ━━━━ PAGE 1: COPERTINA ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
page_num += 1
draw_page_bg(c, BG_COVER)

# Title
c.setFillColor(ACCENT)
c.setFont("Helvetica-Bold", 32)
title = "Animali da Compagnia"
tw = c.stringWidth(title, "Helvetica-Bold", 32)
c.drawString((PAGE_W - tw) / 2, 660, title)

c.setFillColor(DARK)
c.setFont("Helvetica-Bold", 20)
subtitle = "Libro da Colorare per Bambini"
tw = c.stringWidth(subtitle, "Helvetica-Bold", 20)
c.drawString((PAGE_W - tw) / 2, 620, subtitle)

# Dog image on cover - smallish decor
cover_img_path = os.path.join(IMAGES_DIR, "01-cane.png")
img = Image.open(cover_img_path)
img_w, img_h = img.size
max_cov = 250
ratio = min(max_cov / img_w, max_cov / img_h)
dw = img_w * ratio
dh = img_h * ratio
cx = (PAGE_W - dw) / 2
cy = 340
c.drawImage(ImageReader(img), cx, cy, width=dw, height=dh, preserveAspectRatio=True)

# Sales pitches - 3 boxes
pitches = [
    "5 teneri animali da colorare - Cane, Gatto, Coniglio, Criceto e Pesce Rosso",
    "Disegni grandi e facili - Perfetti per piccole mani dai 4 anni in su",
    "Regalo educativo - Stimola creativita, concentrazione e amore per gli animali",
]
box_y_start = 240
for i, pitch in enumerate(pitches):
    box_y = box_y_start - i * 60
    c.setFillColor(white)
    c.setStrokeColor(ACCENT)
    c.setLineWidth(1.5)
    c.roundRect(50, box_y, PAGE_W - 100, 48, 8, fill=1, stroke=1)
    c.setFillColor(DARK)
    c.setFont("Helvetica", 11)
    draw_wrapped_text(c, pitch, 65, box_y + 30, font="Helvetica", size=11, max_width=PAGE_W - 130)

c.showPage()

# ━━━━ PAGE 2: DEDICA ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
page_num += 1
draw_page_bg(c, BG_DEDICA)

c.setFillColor(ACCENT)
c.setFont("Helvetica-Bold", 28)
title_d = "Dedica"
tw = c.stringWidth(title_d, "Helvetica-Bold", 28)
c.drawString((PAGE_W - tw) / 2, 650, title_d)

# Decorative line
c.setStrokeColor(ACCENT)
c.setLineWidth(1)
c.line(200, 635, PAGE_W - 200, 635)

dedica = "A te, piccolo artista, che con i tuoi colori dai vita a ogni amico a quattro zampe (e non solo!). Che ogni pagina sia un'avventura piena di fantasia e tenerezza."

draw_wrapped_text(c, dedica, 60, 580, font="Helvetica", size=16, color=DARK, leading=28, max_width=PAGE_W - 120)

# Name line
c.setFont("Helvetica", 16)
c.setFillColor(GREY)
c.drawString(60, 400, "Da: ___________________________")
c.drawString(60, 370, "Data: __________________________")

c.showPage()

# ━━━━ PAGE 3: INTRODUZIONE GENITORI ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
page_num += 1
draw_page_bg(c, BG_INTRO)

c.setFillColor(ACCENT)
c.setFont("Helvetica-Bold", 28)
title_i = "Introduzione per i Genitori"
tw = c.stringWidth(title_i, "Helvetica-Bold", 28)
c.drawString((PAGE_W - tw) / 2, 680, title_i)

c.setStrokeColor(ACCENT)
c.setLineWidth(1)
c.line(200, 665, PAGE_W - 200, 665)

intro_text = ("Cari genitori, questo libro da colorare e stato pensato per accompagnare "
    "il vostro bambino alla scoperta del meraviglioso mondo degli animali domestici. "
    "Ogni illustrazione e studiata per essere semplice da colorare, stimolante per la "
    "fantasia e adatta a sviluppare la motricita fine dei piu piccoli. "
    "Buon divertimento a tutta la famiglia!")

draw_wrapped_text(c, intro_text, 60, 610, font="Helvetica", size=16, color=DARK, leading=30, max_width=PAGE_W - 120)

c.showPage()

# ━━━━ PAGES 4-8: ILLUSTRAZIONI ──────────────────────────────────────────────
animals = [
    ("01-cane.png", "Cane"),
    ("02-gatto.png", "Gatto"),
    ("03-coniglio.png", "Coniglio"),
    ("04-criceto.png", "Criceto"),
    ("05-pesce-rosso.png", "Pesce Rosso"),
]

for img_file, animal_name in animals:
    page_num += 1
    draw_page_bg(c, BG_ILLUSTRATION)
    
    # Animal name at top
    c.setFillColor(ACCENT)
    c.setFont("Helvetica-Bold", 26)
    tw = c.stringWidth(animal_name, "Helvetica-Bold", 26)
    c.drawString((PAGE_W - tw) / 2, PAGE_H - 60, animal_name)
    
    # Image
    img_path = os.path.join(IMAGES_DIR, img_file)
    add_image_centered_fit(c, img_path, margin=36)
    
    # Page number
    add_page_number(c, page_num, TOTAL_PAGES)
    c.showPage()

# ━━━━ PAGE 9: CTA RECENSIONE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
page_num += 1
draw_page_bg(c, BG_CTA)

c.setFillColor(ACCENT)
c.setFont("Helvetica-Bold", 32)
cta_title = "GRAZIE MILLE!"
tw = c.stringWidth(cta_title, "Helvetica-Bold", 32)
c.drawString((PAGE_W - tw) / 2, 660, cta_title)

cta_text = ("Ci auguriamo che tu e il tuo piccolo artista vi siate divertiti "
    "a colorare gli animali di questo libro. Se ti e piaciuto, ci aiuteresti "
    "tantissimo lasciando una recensione su Amazon? Le tue parole sono preziose "
    "per noi e aiutano altri genitori a scoprire questo libro.\n\n"
    "Clicca Recensione e condividi la tua esperienza!\n\n"
    "A presto con nuove avventure da colorare!")

draw_wrapped_text(c, cta_text, 60, 580, font="Helvetica", size=16, color=DARK, leading=30, max_width=PAGE_W - 120)

# Decorative paw-like shapes
c.setFillColor(ACCENT)
for i, (x, y) in enumerate([(150, 200), (PAGE_W - 150, 200)]):
    c.circle(x, y, 20, fill=1, stroke=0)
    c.circle(x - 30, y + 10, 8, fill=1, stroke=0)
    c.circle(x + 30, y + 10, 8, fill=1, stroke=0)
    c.circle(x - 18, y + 25, 8, fill=1, stroke=0)
    c.circle(x + 18, y + 25, 8, fill=1, stroke=0)

c.showPage()

# ── Save ────────────────────────────────────────────────────────────────────
c.save()

# Report
import os
size_bytes = os.path.getsize(OUTPUT_PDF)
size_mb = size_bytes / (1024 * 1024)
print(f"PDF generated: {OUTPUT_PDF}")
print(f"Pages: {TOTAL_PAGES}")
print(f"Size: {size_bytes} bytes ({size_mb:.2f} MB)")
print("Done!")
