#!/usr/bin/env python3
"""
Build a KDP-ready coloring book PDF from images and copy text.
Format: 8.5x11 inches (612x792 points), 300 DPI images.
"""

import os
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from PIL import Image

BOOK_DIR = "/home/node/.openclaw/workspace/books/animali-della-fattoria"
IMAGES_DIR = os.path.join(BOOK_DIR, "images")
COPY_FILE = os.path.join(BOOK_DIR, "copy.md")
OUTPUT_PDF = os.path.join(BOOK_DIR, "Animali-della-Fattoria-Libro-da-Colorare.pdf")

WIDTH, HEIGHT = letter  # 612 x 792 points (8.5 x 11 inches)
DPI = 300

def parse_copy():
    """Extract sections from copy.md."""
    with open(COPY_FILE, "r", encoding="utf-8") as f:
        text = f.read()

    sections = {}
    
    # Extract dedication
    if "## 6. Testo Pagina Dedica" in text:
        dedica = text.split("## 6. Testo Pagina Dedica")[1].split("##")[0].strip()
        sections["dedica"] = dedica
    
    # Extract intro for parents
    if "## 7. Testo Introduzione per Genitori" in text:
        intro = text.split("## 7. Testo Introduzione per Genitori")[1].split("##")[0].strip()
        sections["intro"] = intro
    
    # Extract CTA
    if "## 8. Testo Pagina Finale" in text:
        cta = text.split("## 8. Testo Pagina Finale")[1].split("##")[0].strip()
        sections["cta"] = cta
    
    return sections

def add_centered_text(c, text, x, y, font_size=14, max_width=500, line_spacing=1.5):
    """Add centered text with word wrap."""
    c.setFont("Helvetica", font_size)
    words = text.split()
    lines = []
    current_line = ""
    for word in words:
        test_line = current_line + " " + word if current_line else word
        if c.stringWidth(test_line, "Helvetica", font_size) < max_width:
            current_line = test_line
        else:
            lines.append(current_line)
            current_line = word
    if current_line:
        lines.append(current_line)
    
    for line in lines:
        c.drawCentredString(WIDTH / 2, y, line)
        y -= font_size * line_spacing
    
    return y

def build_pdf():
    sections = parse_copy()
    c = canvas.Canvas(OUTPUT_PDF, pagesize=letter)
    
    # ============ PAGE 1: COVER ============
    # Background cover image (first image if available)
    cover_img = os.path.join(IMAGES_DIR, "page-01.png")
    if os.path.exists(cover_img):
        img = Image.open(cover_img)
        img_gray = img.convert("L")
        img_rgb = img_gray.convert("RGB")  # keep it B&W line art style
        temp_cover = os.path.join(IMAGES_DIR, "_cover_temp.png")
        img_rgb.save(temp_cover)
        c.drawImage(temp_cover, 0, 0, width=WIDTH, height=HEIGHT, preserveAspectRatio=False)
        os.remove(temp_cover)
    
    # Title on cover
    c.setFillColorRGB(0, 0, 0)
    c.setFont("Helvetica-Bold", 36)
    c.drawCentredString(WIDTH / 2, HEIGHT - 120, "Animali della Fattoria")
    
    c.setFont("Helvetica", 20)
    c.drawCentredString(WIDTH / 2, HEIGHT - 160, "Libro da Colorare per Bambini 3-5 Anni")
    
    c.setFont("Helvetica", 14)
    c.drawCentredString(WIDTH / 2, HEIGHT - 200, "20 illustrazioni semplici e divertenti")
    
    # Decorative text at bottom
    c.setFont("Helvetica-Oblique", 12)
    c.drawCentredString(WIDTH / 2, 80, "Un mondo di animali da colorare!")
    
    c.showPage()
    
    # ============ PAGE 2: DEDICATION ============
    c.setFont("Helvetica-Bold", 24)
    c.drawCentredString(WIDTH / 2, HEIGHT - 150, "Dedica")
    
    if "dedica" in sections:
        c.setFont("Helvetica", 16)
        lines = sections["dedica"].split("\n")
        y = HEIGHT - 220
        for line in lines:
            line = line.strip()
            if line:
                c.drawCentredString(WIDTH / 2, y, line)
                y -= 30
    else:
        c.setFont("Helvetica", 14)
        c.drawCentredString(WIDTH / 2, HEIGHT - 250, "A tutti i piccoli artisti che amano colorare!")
    
    c.showPage()
    
    # ============ PAGE 3: INTRODUCTION FOR PARENTS ============
    c.setFont("Helvetica-Bold", 20)
    c.drawCentredString(WIDTH / 2, HEIGHT - 100, "Caro Genitore,")
    
    if "intro" in sections:
        c.setFont("Helvetica", 13)
        # Split intro into paragraphs
        paragraphs = sections["intro"].split("\n\n")
        y = HEIGHT - 160
        for para in paragraphs:
            para = para.strip()
            if para:
                y = add_centered_text(c, para, WIDTH / 2, y, font_size=13, max_width=480)
                y -= 20
    else:
        c.setFont("Helvetica", 14)
        c.drawCentredString(WIDTH / 2, HEIGHT - 180, "Questo libro aiuta il tuo bambino a sviluppare creatività e manualità.")
    
    c.showPage()
    
    # ============ PAGES 4-23: COLORING PAGES ============
    for i in range(1, 21):
        page_file = os.path.join(IMAGES_DIR, f"page-{i:02d}.png")
        if os.path.exists(page_file):
            # Open and ensure it's suitable for coloring book
            img = Image.open(page_file)
            # Convert to grayscale then back to RGB for clean B&W
            img_gray = img.convert("L")
            img_rgb = img_gray.convert("RGB")
            
            # Resize to fit the page with proper aspect ratio
            img_w, img_h = img_rgb.size
            page_w = int(WIDTH * 0.92)  # Leave margins
            page_h = int(HEIGHT * 0.92)
            
            # Calculate scaling to fit
            scale = min(page_w / img_w, page_h / img_h)
            new_w = int(img_w * scale)
            new_h = int(img_h * scale)
            img_rgb = img_rgb.resize((new_w, new_h), Image.LANCZOS)
            
            # Convert to 300 DPI
            temp_path = os.path.join(IMAGES_DIR, f"_page_{i:02d}_temp.png")
            img_rgb.save(temp_path, dpi=(DPI, DPI))
            
            # Center on page
            x_offset = (WIDTH - new_w * 72 / DPI) / 2
            # Use the image at actual size (scaled already)
            c.drawImage(temp_path, x_offset, (HEIGHT - new_h * 72 / DPI) / 2,
                       width=new_w * 72 / DPI, height=new_h * 72 / DPI)
            
            os.remove(temp_path)
        else:
            c.setFont("Helvetica", 16)
            c.drawCentredString(WIDTH / 2, HEIGHT / 2, f"Pagina {i}")
        
        c.showPage()
    
    # ============ PAGE 24: FINAL CTA ============
    c.setFont("Helvetica-Bold", 22)
    c.drawCentredString(WIDTH / 2, HEIGHT - 150, "Grazie!")
    
    if "cta" in sections:
        c.setFont("Helvetica", 14)
        # Split CTA into paragraphs
        paragraphs = sections["cta"].split("\n\n")
        y = HEIGHT - 220
        for para in paragraphs:
            para = para.strip()
            if para:
                y = add_centered_text(c, para, WIDTH / 2, y, font_size=14, max_width=500)
                y -= 15
                # Handle the emoji line specially
                if "🖍️" in para:
                    c.setFont("Helvetica-Bold", 16)
    else:
        c.setFont("Helvetica", 14)
        c.drawCentredString(WIDTH / 2, HEIGHT - 250, "Ci aiuti a migliorare? Lascia una recensione su Amazon!")
    
    c.save()
    print(f"✅ PDF salvato: {OUTPUT_PDF}")
    print(f"   Dimensione: {os.path.getsize(OUTPUT_PDF) / 1024:.0f} KB")
    print(f"   Pagine: 24 (copertina + dedica + intro + 20 disegni + ringraziamento)")

if __name__ == "__main__":
    build_pdf()
