#!/usr/bin/env python3
"""Build the coloring book PDF for Mostri Simpatici da Colorare."""

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

# Constants
PAGE_W, PAGE_H = letter  # 8.5 x 11 inches
IMAGES_DIR = "/home/node/.openclaw/workspace/books/mostri/images"
OUTPUT_PATH = "/home/node/.openclaw/workspace/books/mostri/mostri.pdf"

# Colors
DARK_PURPLE = HexColor("#2D1B69")
BRIGHT_GREEN = HexColor("#39FF14")
GOLD = HexColor("#FFD700")
HOT_PINK = HexColor("#FF69B4")
CYAN = HexColor("#00FFFF")
ORANGE = HexColor("#FF8C00")
WHITE = white
LIGHT_PURPLE = HexColor("#7B68EE")
SOFT_YELLOW = HexColor("#FFFACD")

# Image files in order
IMAGE_FILES = [
    os.path.join(IMAGES_DIR, "01-mostro-peloso.png"),
    os.path.join(IMAGES_DIR, "02-mostro-tre-teste.png"),
    os.path.join(IMAGES_DIR, "03-mostro-bolle.png"),
    os.path.join(IMAGES_DIR, "04-mostro-tentacoli.png"),
    os.path.join(IMAGES_DIR, "05-mostro-nuvola.png"),
]

MONSTER_NAMES = [
    "Mostro Peloso",
    "Mostro Tre Teste",
    "Mostro delle Bolle",
    "Mostro Tentacolato",
    "Mostro Nuvola",
]

def draw_rounded_rect(c, x, y, w, h, r, color, stroke_color=None, stroke_width=0):
    """Draw a rounded rectangle."""
    c.setFillColor(color)
    if stroke_color and stroke_width > 0:
        c.setStrokeColor(stroke_color)
        c.setLineWidth(stroke_width)
    else:
        c.setStrokeColor(color)
    c.roundRect(x, y, w, h, r, fill=1, stroke=(stroke_color is not None and stroke_width > 0))

def draw_star(c, cx, cy, r, fill_color, stroke_color=None):
    """Draw a 5-pointed star."""
    import math
    points = []
    for i in range(5):
        angle = -math.pi/2 + i * 2*math.pi/5
        outer_x = cx + r * math.cos(angle)
        outer_y = cy + r * math.sin(angle)
        inner_angle = angle + math.pi/5
        inner_r = r * 0.4
        inner_x = cx + inner_r * math.cos(inner_angle)
        inner_y = cy + inner_r * math.sin(inner_angle)
        points.extend([outer_x, outer_y, inner_x, inner_y])
    c.setFillColor(fill_color)
    if stroke_color:
        c.setStrokeColor(stroke_color)
    else:
        c.setStrokeColor(fill_color)
    c.setLineWidth(1)
    path = c.beginPath()
    path.moveTo(points[0], points[1])
    for i in range(1, len(points)//2):
        path.lineTo(points[2*i], points[2*i+1])
    path.close()
    c.drawPath(path, fill=1, stroke=1)

def draw_cover(c):
    """Page 1: Cover page."""
    # Full page background
    c.setFillColor(DARK_PURPLE)
    c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)
    
    # Decorative elements - stars
    import random
    random.seed(42)
    for _ in range(25):
        sx = random.uniform(0.2*inch, PAGE_W - 0.2*inch)
        sy = random.uniform(0.2*inch, PAGE_H - 0.2*inch)
        sr = random.uniform(4, 12)
        colors = [GOLD, HOT_PINK, CYAN, ORANGE]
        draw_star(c, sx, sy, sr, random.choice(colors))
    
    # Decorative circles
    for _ in range(8):
        cx = random.uniform(0.5*inch, PAGE_W - 0.5*inch)
        cy = random.uniform(0.5*inch, PAGE_H - 0.5*inch)
        cr = random.uniform(15, 35)
        alpha_colors = [
            HexColor("#FF69B440"),
            HexColor("#00FFFF40"),
            HexColor("#FFD70040"),
            HexColor("#39FF1440"),
        ]
        c.setFillColor(random.choice(alpha_colors))
        c.circle(cx, cy, cr, fill=1, stroke=0)
    
    # Title
    c.setFillColor(GOLD)
    c.setFont("Helvetica-Bold", 42)
    title = "Mostri Simpatici"
    title_w = c.stringWidth(title, "Helvetica-Bold", 42)
    c.drawString((PAGE_W - title_w) / 2, PAGE_H - 2.3*inch, title)
    
    c.setFont("Helvetica-Bold", 34)
    subtitle = "da Colorare"
    sub_w = c.stringWidth(subtitle, "Helvetica-Bold", 34)
    c.drawString((PAGE_W - sub_w) / 2, PAGE_H - 2.9*inch, subtitle)
    
    c.setFillColor(HOT_PINK)
    c.setFont("Helvetica-Oblique", 20)
    tagline = "5 Mostri Buffi che Non Fanno Paura!"
    tag_w = c.stringWidth(tagline, "Helvetica-Oblique", 20)
    c.drawString((PAGE_W - tag_w) / 2, PAGE_H - 3.4*inch, tagline)
    
    # Cover image - mostro peloso
    img_path = IMAGE_FILES[0]
    c.drawImage(img_path, 
                PAGE_W/2 - 1.3*inch, PAGE_H - 5.5*inch - 1.3*inch,
                2.6*inch, 2.6*inch, preserveAspectRatio=True)
    
    # 3 Leve di vendita in box
    leve = [
        "🧸 5 Mostri BUFFI — NESSUNO FA PAURA!",
        "🖍️  Disegni FACILI — Linee Spesse e Aree Ampie",
        "🎁  Regalo Originale per Stimolare la Creatività",
    ]
    
    box_y_start = 1.5*inch
    box_h = 0.55*inch
    box_w = 6.0*inch
    box_x = (PAGE_W - box_w) / 2
    gap = 0.15*inch
    
    box_colors = [BRIGHT_GREEN, CYAN, ORANGE]
    box_text_colors = [HexColor("#003300"), HexColor("#000066"), HexColor("#331100")]
    
    for i, leva in enumerate(leve):
        y = box_y_start + i * (box_h + gap)
        # Shadow
        draw_rounded_rect(c, box_x + 0.04*inch, y - 0.04*inch, box_w, box_h, 10, 
                         HexColor("#1A0E3D"))
        # Box
        draw_rounded_rect(c, box_x, y, box_w, box_h, 10, box_colors[i])
        # Text
        c.setFillColor(box_text_colors[i])
        c.setFont("Helvetica-Bold", 14)
        c.drawString(box_x + 0.3*inch, y + 0.15*inch, leva)
    
    # Bottom tag
    c.setFillColor(WHITE)
    c.setFont("Helvetica", 12)
    c.drawCentredString(PAGE_W/2, 0.4*inch, "Disegnato per Bambini dai 3 ai 7 Anni")

def draw_dedica(c):
    """Page 2: Dedica."""
    # Background
    c.setFillColor(HexColor("#FFFACD"))
    c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)
    
    # Decorative frame
    c.setStrokeColor(DARK_PURPLE)
    c.setLineWidth(3)
    c.rect(0.5*inch, 0.5*inch, PAGE_W - inch, PAGE_H - inch, fill=0, stroke=1)
    
    # Inner frame
    c.setStrokeColor(HOT_PINK)
    c.setLineWidth(1)
    c.setDash(4, 4)
    c.rect(0.7*inch, 0.7*inch, PAGE_W - 1.4*inch, PAGE_H - 1.4*inch, fill=0, stroke=1)
    c.setDash()
    
    # Small decorative stars
    draw_star(c, 1.2*inch, PAGE_H - 1.2*inch, 10, GOLD)
    draw_star(c, PAGE_W - 1.2*inch, PAGE_H - 1.2*inch, 10, GOLD)
    draw_star(c, 1.2*inch, 1.2*inch, 10, GOLD)
    draw_star(c, PAGE_W - 1.2*inch, 1.2*inch, 10, GOLD)
    
    # Dedica title
    c.setFillColor(DARK_PURPLE)
    c.setFont("Helvetica-Bold", 28)
    c.drawCentredString(PAGE_W/2, PAGE_H - 2.0*inch, "Dedica")
    
    # Decorative line
    c.setStrokeColor(HOT_PINK)
    c.setLineWidth(2)
    c.line(2.5*inch, PAGE_H - 2.3*inch, PAGE_W - 2.5*inch, PAGE_H - 2.3*inch)
    
    # Dedica text
    c.setFillColor(DARK_PURPLE)
    c.setFont("Helvetica-Oblique", 22)
    dedica_text = "A tutti i bambini che sanno"
    c.drawCentredString(PAGE_W/2, PAGE_H - 3.0*inch, dedica_text)
    
    c.setFont("Helvetica-Oblique", 24)
    dedica_text2 = "che i mostri veri non esistono..."
    c.drawCentredString(PAGE_W/2, PAGE_H - 3.6*inch, dedica_text2)
    
    c.setFont("Helvetica-Bold", 26)
    dedica_text3 = "ma quelli buffi sì!"
    c.drawCentredString(PAGE_W/2, PAGE_H - 4.3*inch, dedica_text3)
    
    # Monster doodle (small)
    monster_faces = ["👹", "👾", "👻", "😈"]
    c.setFont("Helvetica", 30)
    for i, face in enumerate(monster_faces):
        x = 1.5*inch + i * 2.0*inch
        c.drawString(x, 1.8*inch, face)

def draw_intro(c):
    """Page 3: Introduzione per genitori."""
    # Background
    c.setFillColor(WHITE)
    c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)
    
    # Decorative header band
    c.setFillColor(DARK_PURPLE)
    c.rect(0, PAGE_H - 1.2*inch, PAGE_W, 1.2*inch, fill=1, stroke=0)
    c.setFillColor(GOLD)
    c.setFont("Helvetica-Bold", 26)
    c.drawCentredString(PAGE_W/2, PAGE_H - 0.85*inch, "Ai Genitori")
    
    # Intro text
    intro_lines = [
        "Cari genitori,",
        "",
        "Questo libro è stato pensato per far divertire i vostri",
        "bambini con personaggi buffi, teneri e assolutamente",
        "NON spaventosi.",
        "",
        "I disegni dalle linee spesse e le aree ampie permettono",
        "anche ai più piccoli di colorare con facilità, sviluppando",
        "creatività e manualità in un ambiente sereno e giocoso.",
        "",
        "Sedetevi accanto a loro, colorate insieme e scoprite",
        "il mondo meraviglioso dei mostri simpatici!",
    ]
    
    c.setFillColor(HexColor("#333333"))
    c.setFont("Helvetica", 16)
    y = PAGE_H - 2.0*inch
    for line in intro_lines:
        if line == "":
            y -= 0.2*inch
        else:
            c.drawCentredString(PAGE_W/2, y, line)
            y -= 0.45*inch
    
    # Decorative bottom
    c.setFillColor(LIGHT_PURPLE)
    c.setFont("Helvetica", 14)
    c.drawCentredString(PAGE_W/2, 1.0*inch, "✧ Buon divertimento! ✧")

def draw_illustration_page(c, img_path, monster_name, page_num):
    """Draw an illustration page with image centered and monster name at top."""
    # White background
    c.setFillColor(WHITE)
    c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)
    
    # Decorative top bar
    c.setFillColor(DARK_PURPLE)
    c.rect(0, PAGE_H - 0.9*inch, PAGE_W, 0.9*inch, fill=1, stroke=0)
    
    # Monster name
    c.setFillColor(GOLD)
    c.setFont("Helvetica-Bold", 22)
    c.drawCentredString(PAGE_W/2, PAGE_H - 0.65*inch, monster_name)
    
    # Page number
    c.setFillColor(HexColor("#AAAAAA"))
    c.setFont("Helvetica", 10)
    c.drawCentredString(PAGE_W/2, 0.25*inch, f"{page_num}")
    
    # Draw the image centered on page
    # Leave room: top 0.9in header, bottom 0.5in
    img_area_top = PAGE_H - 1.1*inch
    img_area_bottom = 0.5*inch
    img_area_h = img_area_top - img_area_bottom
    img_area_w = PAGE_W - 1.0*inch  # 0.5in margins each side
    
    # Fit image within the area while preserving aspect ratio
    c.drawImage(img_path, 
                (PAGE_W - min(img_area_w, img_area_h))/2,
                img_area_bottom + (img_area_h - min(img_area_w, img_area_h))/2,
                min(img_area_w, img_area_h),
                min(img_area_w, img_area_h),
                preserveAspectRatio=True)

def draw_cta(c):
    """Last page: Call to action for review."""
    # Background
    c.setFillColor(HexColor("#FFF0F5"))
    c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)
    
    # Decorative frame
    c.setStrokeColor(HOT_PINK)
    c.setLineWidth(2)
    c.rect(0.5*inch, 0.5*inch, PAGE_W - inch, PAGE_H - inch, fill=0, stroke=1)
    
    # Dotted inner frame
    c.setStrokeColor(LIGHT_PURPLE)
    c.setLineWidth(1)
    c.setDash(3, 3)
    c.rect(0.7*inch, 0.7*inch, PAGE_W - 1.4*inch, PAGE_H - 1.4*inch, fill=0, stroke=1)
    c.setDash()
    
    # CTA content
    c.setFillColor(DARK_PURPLE)
    c.setFont("Helvetica-Bold", 24)
    c.drawCentredString(PAGE_W/2, PAGE_H - 1.8*inch, "Grazie!")
    
    c.setFont("Helvetica", 16)
    c.setFillColor(HexColor("#555555"))
    c.drawCentredString(PAGE_W/2, PAGE_H - 2.4*inch, "Grazie per aver colorato con noi!")
    
    # Main CTA text
    c.setFillColor(HexColor("#333333"))
    c.setFont("Helvetica", 14)
    
    cta_lines = [
        "Se questo libro ha fatto sorridere il vostro bambino,",
        "ci aiutereste tantissimo lasciando",
        "una recensione su Amazon?",
        "",
        "Bastano poche parole per far sì che altri genitori",
        "scoprano i nostri mostri buffi!",
        "",
        "E ricordate:",
    ]
    
    y = PAGE_H - 3.2*inch
    for line in cta_lines:
        if line == "":
            y -= 0.2*inch
        else:
            c.drawCentredString(PAGE_W/2, y, line)
            y -= 0.4*inch
    
    # Final line - highlighted
    c.setFillColor(HOT_PINK)
    c.setFont("Helvetica-BoldOblique", 18)
    c.drawCentredString(PAGE_W/2, y - 0.15*inch, "più colori, meno paure! 🎨")
    
    # Decorative monsters at bottom
    monster_emoji = ["👹", "👾", "👻", "😈", "🤡"]
    c.setFont("Helvetica", 28)
    for i, emoji in enumerate(monster_emoji):
        x = 0.7*inch + i * 1.7*inch
        c.drawString(x, 1.2*inch, emoji)


def main():
    c = canvas.Canvas(OUTPUT_PATH, pagesize=letter)
    
    # Page 1: Cover
    print("📖 Generating cover page...")
    draw_cover(c)
    c.showPage()
    
    # Page 2: Dedica
    print("📖 Generating dedica page...")
    draw_dedica(c)
    c.showPage()
    
    # Page 3: Introduzione
    print("📖 Generating introduzione page...")
    draw_intro(c)
    c.showPage()
    
    # Pages 4-8: Illustrations
    for i, (img_path, name) in enumerate(zip(IMAGE_FILES, MONSTER_NAMES)):
        print(f"📖 Generating illustration page {i+1}: {name}...")
        draw_illustration_page(c, img_path, name, i + 4)
        c.showPage()
    
    # Last page: CTA
    print("📖 Generating CTA page...")
    draw_cta(c)
    c.showPage()
    
    # Save
    c.save()
    
    file_size = os.path.getsize(OUTPUT_PATH)
    print(f"\n✅ PDF generated successfully!")
    print(f"   Path: {OUTPUT_PATH}")
    print(f"   Size: {file_size:,} bytes ({file_size/1024:.1f} KB)")
    print(f"   Pages: 8 (Cover, Dedica, Introduzione, 5 Illustrations, CTA)")


if __name__ == "__main__":
    main()
