#!/usr/bin/env python3
"""
生成绘本 PDF Demo v2 - 使用 Pillow 渲染中文
Pillow 可以正确显示系统字体中的中文
"""

from PIL import Image, ImageDraw, ImageFont
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.lib import colors
from reportlab.platypus import Image as RLImage
from reportlab.lib.units import cm
import os

# 配置
OUTPUT_DIR = "/root/.openclaw/workspace/trilingual-picturebook/output"
PDF_OUTPUT = "/root/.openclaw/workspace/trilingual-picturebook/demo/带文案 demo-第 13-14 页.pdf"
TEMP_DIR = "/root/.openclaw/workspace/trilingual-picturebook/demo/.temp"

# 图片路径
IMG_13 = os.path.join(OUTPUT_DIR, "gemini-page-13.png")
IMG_14 = os.path.join(OUTPUT_DIR, "gemini-page-14.png")

# 创建临时目录
os.makedirs(TEMP_DIR, exist_ok=True)

# PDF 尺寸 - A4 横向
PAGE_WIDTH = 29.7 * cm
PAGE_HEIGHT = 21 * cm
DPI = 150

# 边距
MARGIN_CM = 1.5 * cm


def find_chinese_font():
    """查找可用的中文字体"""
    font_paths = [
        "/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc",
        "/usr/share/fonts/google-noto-cjk/NotoSansCJK-Black.ttc",
        "/usr/share/fonts/google-noto-cjk/NotoSerifCJK-Regular.ttc",
        "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
    ]
    
    for path in font_paths:
        if os.path.exists(path):
            return path
    
    # 尝试使用默认字体
    return None


def create_text_image(text_lines, width_px, height_px, filename):
    """使用 Pillow 创建带中文的文字图片"""
    
    # 创建白色背景图片
    img = Image.new('RGB', (width_px, height_px), color='#FFFDF5')
    draw = ImageDraw.Draw(img)
    
    # 加载中文字体
    font_path = find_chinese_font()
    
    if font_path:
        try:
            # TTC 文件需要指定字体索引，尝试不同的 size
            font_regular = ImageFont.truetype(font_path, 24)
            font_bold = ImageFont.truetype(font_path, 28)
            print(f"   ✅ 字体：{font_path}")
        except Exception as e:
            print(f"   ⚠️  字体加载失败：{e}，使用默认字体")
            font_regular = ImageFont.load_default()
            font_bold = ImageFont.load_default()
    else:
        print("   ⚠️  未找到中文字体，使用默认字体")
        font_regular = ImageFont.load_default()
        font_bold = ImageFont.load_default()
    
    # 绘制文字
    y_offset = 20
    line_height = 40
    
    for i, (text, is_bold) in enumerate(text_lines):
        font = font_bold if is_bold else font_regular
        draw.text((20, y_offset + i * line_height), text, fill='#333333', font=font)
    
    # 保存图片
    img.save(filename)
    print(f"   ✅ 文字图片：{filename}")
    return filename


def create_pdf_demo():
    """创建 PDF Demo"""
    
    print("📄 创建 PDF Demo: 第 13-14 页跨页")
    print(f"   尺寸：{PAGE_WIDTH/cm:.1f}cm x {PAGE_HEIGHT/cm:.1f}cm")
    
    # 计算图片尺寸（像素）
    img_width_px = int(((PAGE_WIDTH - 3 * MARGIN_CM) / 2) / cm * DPI)
    img_height_px = int((PAGE_HEIGHT * 0.55) / cm * DPI)
    
    # 创建文字图片
    text_lines_left = [
        ("哥哥妹妹，下楼吃早餐", True),
        ("哥哥妹妹，落樓食早餐", False),
        ("阿兄阿妹，落樓食早頓", False),
    ]
    
    text_lines_right = [
        ("旺財說：「汪汪！早上好！」", True),
        ("旺財說：「汪汪！早晨！」", False),
        ("旺財講：「汪汪！早！」", False),
    ]
    
    text_img_width = int((PAGE_WIDTH / 2 - MARGIN_CM) / cm * DPI)
    text_img_height = 150
    
    text_left_path = create_text_image(
        text_lines_left, 
        text_img_width, 
        text_img_height, 
        os.path.join(TEMP_DIR, "text_left.png")
    )
    
    text_right_path = create_text_image(
        text_lines_right, 
        text_img_width, 
        text_img_height, 
        os.path.join(TEMP_DIR, "text_right.png")
    )
    
    # 创建 PDF
    c = canvas.Canvas(PDF_OUTPUT, pagesize=A4)
    c.setPageSize((PAGE_WIDTH, PAGE_HEIGHT))
    
    # 背景
    c.setFillColor(colors.HexColor("#FFFDF5"))
    c.rect(0, 0, PAGE_WIDTH, PAGE_HEIGHT, fill=True, stroke=False)
    
    # 左页图片
    img_width = (PAGE_WIDTH - 3 * MARGIN_CM) / 2
    img_height = PAGE_HEIGHT * 0.55
    img_x_left = MARGIN_CM
    img_y = PAGE_HEIGHT - MARGIN_CM - img_height
    
    if os.path.exists(IMG_13):
        img_obj = RLImage(IMG_13, width=img_width, height=img_height)
        img_obj.drawOn(c, img_x_left, img_y)
        print(f"   ✅ 左页图片：{IMG_13}")
    
    # 右页图片
    img_x_right = MARGIN_CM * 2 + img_width
    
    if os.path.exists(IMG_14):
        img_obj = RLImage(IMG_14, width=img_width, height=img_height)
        img_obj.drawOn(c, img_x_right, img_y)
        print(f"   ✅ 右页图片：{IMG_14}")
    
    # 分割线
    c.setStrokeColor(colors.HexColor("#DDDDDD"))
    c.setLineWidth(1)
    c.line(MARGIN_CM, img_y - 0.3 * cm, PAGE_WIDTH - MARGIN_CM, img_y - 0.3 * cm)
    
    # 左页文字
    text_y = img_y - 1.5 * cm
    text_img_obj = RLImage(text_left_path, width=(PAGE_WIDTH/2 - MARGIN_CM), height=text_img_height/DPI*cm)
    text_img_obj.drawOn(c, MARGIN_CM, text_y - 0.5 * cm)
    
    # 右页文字
    text_img_obj = RLImage(text_right_path, width=(PAGE_WIDTH/2 - MARGIN_CM), height=text_img_height/DPI*cm)
    text_img_obj.drawOn(c, img_x_right, text_y - 0.5 * cm)
    
    # QR 码占位框
    qr_size = 2.5 * cm
    qr_x = PAGE_WIDTH - MARGIN_CM - qr_size
    qr_y = MARGIN_CM
    c.setStrokeColor(colors.HexColor("#4A90D9"))
    c.setLineWidth(2)
    c.rect(qr_x, qr_y, qr_size, qr_size, fill=False, stroke=True)
    c.setFillColor(colors.HexColor("#4A90D9"))
    c.setFont("Helvetica", 10)
    c.drawCentredString(qr_x + qr_size/2, qr_y + qr_size/2 - 5, "QR 码")
    c.drawCentredString(qr_x + qr_size/2, qr_y + qr_size/2 - 15, "听音频")
    
    # 页码
    c.setFillColor(colors.gray)
    c.setFont("Helvetica", 9)
    c.drawCentredString(PAGE_WIDTH/2, MARGIN_CM - 0.5 * cm, "第 13-14 页 · 哥哥妹妹早上好")
    
    # 质量标注
    c.setFillColor(colors.HexColor("#888888"))
    c.setFont("Helvetica-Oblique", 8)
    c.drawString(MARGIN_CM, PAGE_HEIGHT - 0.8 * cm, f"图片质量：1k (512×512) | 生成：2026-03-02")
    
    c.save()
    
    # 清理临时文件
    for f in [text_left_path, text_right_path]:
        if os.path.exists(f):
            os.remove(f)
    
    print(f"\n✅ PDF 已保存：{PDF_OUTPUT}")
    file_size = os.path.getsize(PDF_OUTPUT) / 1024
    print(f"   文件大小：{file_size:.1f} KB")
    
    return PDF_OUTPUT


if __name__ == "__main__":
    create_pdf_demo()
