#!/usr/bin/env python3
"""
Format the Dinosaur Coloring Book into a KDP-ready PDF.
8.5x11" at 300 DPI, black & white interior, single-sided pages.
Uses img2pdf for PDF compilation.
"""

from PIL import Image, ImageDraw, ImageFont
import os, tempfile, subprocess

W, H = 2550, 3300  # 8.5x11" at 300 DPI
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)

OUT_DIR = "/home/node/.openclaw/workspace/books/dinosauri-colorare"
IMG_DIR = os.path.join(OUT_DIR, "images")
TMP_DIR = os.path.join(OUT_DIR, "tmp_pages")
os.makedirs(TMP_DIR, exist_ok=True)

def find_font(weight="Bold", size=80):
    """Find the best available font."""
    candidates = [
        f"/usr/share/fonts/truetype/dejavu/DejaVuSans-{weight}.ttf",
        f"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
        "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
        "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
        "/usr/share/fonts/TTF/DejaVuSans.ttf",
    ]
    for c in candidates:
        if os.path.exists(c):
            try:
                return ImageFont.truetype(c, size)
            except Exception:
                pass
    for root, dirs, files in os.walk("/usr/share/fonts"):
        for f in files:
            if f.endswith(".ttf") and "DejaVu" in f:
                try:
                    return ImageFont.truetype(os.path.join(root, f), size)
                except Exception:
                    pass
    return ImageFont.load_default()

def draw_text_centered(draw, text, font, y):
    """Draw text centered horizontally."""
    bbox = draw.textbbox((0, 0), text, font=font)
    tw = bbox[2] - bbox[0]
    draw.text(((W - tw) // 2, y), text, fill=BLACK, font=font)
    return y + (bbox[3] - bbox[1]) + 15

def make_text_page(lines, font_size=60, title=None, title_size=80, line_spacing=1.5):
    """Create a page with centered text with word wrap."""
    img = Image.new("RGB", (W, H), WHITE)
    draw = ImageDraw.Draw(img)
    
    margin = 200
    usable_w = W - 2 * margin
    font = find_font("Regular", font_size)
    
    y_start = H // 3
    if title:
        font_title = find_font("Bold", title_size)
        tw = draw.textbbox((0, 0), title, font=font_title)[2]
        draw.text(((W - tw) // 2, 400), title, fill=BLACK, font=font_title)
        y_start = 700
    
    y = y_start
    for line in lines:
        if not line.strip():
            y += font_size
            continue
        words = line.split()
        current = ""
        for word in words:
            test = (current + " " + word).strip()
            tw = draw.textbbox((0, 0), test, font=font)[2]
            if tw > usable_w and current:
                tw2 = draw.textbbox((0, 0), current, font=font)[2]
                draw.text(((W - tw2) // 2, y), current, fill=BLACK, font=font)
                y += int(font_size * 1.6)
                current = word
            else:
                current = test
        if current:
            tw = draw.textbbox((0, 0), current, font=font)[2]
            draw.text(((W - tw) // 2, y), current, fill=BLACK, font=font)
            y += int(font_size * 1.6)
        else:
            y += font_size
    return img

def make_cover():
    """Create the cover page with title."""
    img = Image.new("RGB", (W, H), WHITE)
    draw = ImageDraw.Draw(img)
    
    # Decorative border
    draw.rectangle([40, 40, W-40, H-40], outline=BLACK, width=12)
    draw.rectangle([60, 60, W-60, H-60], outline=GRAY, width=4)
    
    # Decorative corner dinos (small)
    # Top-left corner art
    corner_size = 80
    draw.line([120, 200, 120, 120, 200, 120], fill=BLACK, width=6)
    draw.line([W-200, 120, W-120, 120, W-120, 200], fill=BLACK, width=6)
    draw.line([120, H-120, 120, H-200, 200, H-120], fill=BLACK, width=6)
    draw.line([W-200, H-120, W-120, H-120, W-120, H-200], fill=BLACK, width=6)
    
    # Main title
    y = 350
    title_font = find_font("Bold", 150)
    y = draw_text_centered(draw, "DINOSAUR", title_font, y)
    title_font2 = find_font("Bold", 130)
    y = draw_text_centered(draw, "COLORING BOOK", title_font2, y+40)
    
    # Subtitle
    sub_font = find_font("Regular", 72)
    y = draw_text_centered(draw, "for Kids Ages 4-7", sub_font, y+80)
    
    # Divider
    y += 40
    draw.line([W//3, y, 2*W//3, y], fill=BLACK, width=4)
    y += 50
    
    sub2_font = find_font("Regular", 60)
    y = draw_text_centered(draw, "20 Cute & Easy Dino Pages", sub2_font, y)
    y = draw_text_centered(draw, "for Boys and Girls", sub2_font, y+50)
    
    # Dino emoji art (larger)
    y += 50
    dino_font = find_font("Regular", 200)
    y = draw_text_centered(draw, "🦕  🦖  🦕", dino_font, y)
    
    # Bottom info
    info_font = find_font("Regular", 50)
    draw_text_centered(draw, "Bold & Easy Designs  •  Single-Sided Pages", info_font, H - 280)
    
    return img

def make_dedication():
    """Create the dedication page."""
    lines = [
        "",
        "",
        "",
        "To the bravest little explorer:",
        "",
        "",
        "This book belongs to ____________________",
        "",
        "",
        "May your imagination be as big as a dinosaur's heart",
        "and your colors as bright as a prehistoric sunrise.",
        "Every page is a new adventure — have fun!",
    ]
    return make_text_page(lines, font_size=70)

def make_introduction():
    """Create the parent introduction page."""
    title = "A Note for Grown-Ups"
    lines = [
        "",
        "Coloring is more than just fun — it's a powerful tool",
        "for your child's development. As your little one fills",
        "these pages with color, they're building fine motor skills,",
        "strengthening hand muscles for writing, and learning to",
        "focus on a task.",
        "",
        "The simple, bold illustrations in this book are designed",
        "to build confidence: your child can color them beautifully",
        "without frustration.",
        "",
        "So grab some crayons, sit together, and watch their",
        "creativity take flight. Every finished page is a small",
        "victory worth celebrating!",
    ]
    return make_text_page(lines, font_size=60, title=title, title_size=90)

def make_final_page():
    """Create the final congratulations/review CTA page."""
    img = Image.new("RGB", (W, H), WHITE)
    draw = ImageDraw.Draw(img)
    
    # Border
    draw.rectangle([40, 40, W-40, H-40], outline=BLACK, width=8)
    draw.rectangle([60, 60, W-60, H-60], outline=GRAY, width=3)
    
    # Big title
    font_t = find_font("Bold", 100)
    draw_text_centered(draw, "Congratulations,", font_t, 350)
    draw_text_centered(draw, "Little Artist!", font_t, 470)
    
    # Message
    font_m = find_font("Regular", 65)
    y = 650
    msg_lines = [
        "You colored all 20 dinosaurs! 🎉",
        "",
        "You've traveled through prehistoric times",
        "and filled this book with amazing colors.",
        "You should be so proud of yourself!",
    ]
    for line in msg_lines:
        y = draw_text_centered(draw, line, font_m, y)
    
    # Separator
    y += 40
    draw.line([W//3, y, 2*W//3, y], fill=BLACK, width=4)
    y += 70
    
    # Parent CTA
    font_cta = find_font("Bold", 55)
    y = draw_text_centered(draw, "A big favor for parents:", font_cta, y)
    
    font_cta2 = find_font("Regular", 50)
    y = draw_text_centered(draw, "If you and your child enjoyed this coloring book,", font_cta2, y+20)
    y = draw_text_centered(draw, "we'd be so grateful if you could leave a", font_cta2, y)
    y = draw_text_centered(draw, "review on Amazon.", font_cta2, y)
    
    y += 20
    y = draw_text_centered(draw, "Your feedback helps other parents discover", font_cta2, y)
    y = draw_text_centered(draw, "the perfect activity book for their little ones!", font_cta2, y)
    
    y += 40
    draw_text_centered(draw, "❤️  Thank you for coloring with us!  ❤️", font_cta, y)
    
    return img

def main():
    page_images = []
    
    print("📄 Creating cover page...")
    cover = make_cover()
    cover_path = os.path.join(TMP_DIR, "00-cover.png")
    cover.save(cover_path, "PNG")
    page_images.append(cover_path)
    
    print("📄 Creating dedication page...")
    ded = make_dedication()
    ded_path = os.path.join(TMP_DIR, "00-dedication.png")
    ded.save(ded_path, "PNG")
    page_images.append(ded_path)
    
    print("📄 Creating introduction page...")
    intro = make_introduction()
    intro_path = os.path.join(TMP_DIR, "00-introduction.png")
    intro.save(intro_path, "PNG")
    page_images.append(intro_path)
    
    # Add all coloring pages
    img_files = sorted([f for f in os.listdir(IMG_DIR) if f.endswith(".png")])
    for img_file in img_files:
        print(f"   Adding {img_file}...")
        src_path = os.path.join(IMG_DIR, img_file)
        # Copy to temp dir with consistent naming
        dst_path = os.path.join(TMP_DIR, img_file)
        Image.open(src_path).convert("RGB").save(dst_path, "PNG")
        page_images.append(dst_path)
    
    print("📄 Creating final page (CTA)...")
    final = make_final_page()
    final_path = os.path.join(TMP_DIR, "99-final.png")
    final.save(final_path, "PNG")
    page_images.append(final_path)
    
    # Combine into PDF using img2pdf
    out_path = os.path.join(OUT_DIR, "dinosaur-coloring-book-ages-4-7.pdf")
    print(f"\n💾 Combining {len(page_images)} pages into PDF...")
    
    import img2pdf
    
    # 8.5x11 inches = 612x792 points (at 72 DPI)
    PAGE_W_PT = 612
    PAGE_H_PT = 792
    
    layout = img2pdf.get_layout_fun((PAGE_W_PT, PAGE_H_PT))
    
    with open(out_path, "wb") as f:
        f.write(img2pdf.convert(
            page_images,
            layout_fun=layout,
        ))
    
    file_size = os.path.getsize(out_path)
    print(f"✅ PDF generated successfully!")
    print(f"   Pages: {len(page_images)}")
    print(f"   Size: {file_size / 1024 / 1024:.1f} MB")
    print(f"   File: {out_path}")
    
    # Clean up temp files
    import shutil
    shutil.rmtree(TMP_DIR, ignore_errors=True)
    
    return out_path

if __name__ == "__main__":
    main()
