#!/usr/bin/env python3
"""
生成枪炮、病菌与钢铁的所有字幕图片（adid=8096）
"""
import sqlite3
import os
from PIL import Image, ImageDraw, ImageFont

db_path = "\\\\ll\\D\\xtrssvjj\\dpd.db"
frames_dir = "shitu_frames"

# 清理旧目录
if os.path.exists(frames_dir):
    for file in os.listdir(frames_dir):
        os.remove(os.path.join(frames_dir, file))
else:
    os.makedirs(frames_dir)

# 字体设置
font_paths = [
    "C:/Windows/Fonts/msyh.ttc",
    "C:/Windows/Fonts/simhei.ttf",
    "C:/Windows/Fonts/simsun.ttc"
]
font_path = None
for fp in font_paths:
    if os.path.exists(fp):
        font_path = fp
        break

if not font_path:
    print("错误: 找不到中文字体")
    exit(1)

# 字体大小（更大）
title_font = ImageFont.truetype(font_path, 58)  # 标题58px
subtitle_font = ImageFont.truetype(font_path, 44)  # 副标题44px
cn_font = ImageFont.truetype(font_path, 66)  # 中文66px（更大）
en_font = ImageFont.truetype(font_path, 66)  # 英文66px（和中文一致）

def wrap_text(text, font, max_width):
    """自动换行"""
    words = list(text)
    lines = []
    current_line = []
    for word in words:
        test_line = ''.join(current_line + [word])
        bbox = font.getbbox(test_line)
        text_width = bbox[2] - bbox[0]
        if text_width <= max_width:
            current_line.append(word)
        else:
            if current_line:
                lines.append(''.join(current_line))
            current_line = [word]
    if current_line:
        lines.append(''.join(current_line))
    return lines

def create_frame(title, subtitle, cn_text, en_text, output_path):
    """生成单帧图片"""
    width, height = 1080, 1920
    img = Image.new('RGB', (width, height), color='#1a1a2e')
    draw = ImageDraw.Draw(img)

    # 标题（白色，自动换行）
    max_width = width - 100
    title_lines = wrap_text(title, title_font, max_width)
    y_offset = 120
    for line in title_lines:
        line_bbox = draw.textbbox((0, 0), line, font=title_font)
        line_width = line_bbox[2] - line_bbox[0]
        draw.text(((width - line_width) // 2, y_offset), line, font=title_font, fill='white')
        y_offset += 70

    # 副题与标题隔开一行
    y_offset += 40

    # 副标题（白色）
    sub_bbox = draw.textbbox((0, 0), subtitle, font=subtitle_font)
    sub_width = sub_bbox[2] - sub_bbox[0]
    draw.text(((width - sub_width) // 2, y_offset), subtitle, font=subtitle_font, fill='white')

    # 再隔五行显示下面的字幕
    y_offset += 40 + 5 * 40  # 40px间隔 + 5行空行

    # 中文（黄色，自动换行）
    cn_lines = wrap_text(cn_text, cn_font, max_width)
    for line in cn_lines:
        line_bbox = draw.textbbox((0, 0), line, font=cn_font)
        line_width = line_bbox[2] - line_bbox[0]
        draw.text(((width - line_width) // 2, y_offset), line, font=cn_font, fill='#FFD700')
        y_offset += 100

    # 英文（白色，自动换行）
    y_offset += 30
    en_lines = wrap_text(en_text, en_font, max_width)
    for line in en_lines:
        line_bbox = draw.textbbox((0, 0), line, font=en_font)
        line_width = line_bbox[2] - line_bbox[0]
        draw.text(((width - line_width) // 2, y_offset), line, font=en_font, fill='white')
        y_offset += 100

    img.save(output_path, quality=95)

# 查询所有字幕
try:
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute("SELECT idx, cn, en FROM srts WHERE adid = 8096 ORDER BY idx ASC")
    subtitles = cursor.fetchall()

    print(f"生成 {len(subtitles)} 帧字幕图片...")

    title = "高晓松向马云推荐的三本书之一《枪炮_病菌与钢铁》: 我们人类到底是怎么一步步走到今天这个样子的"
    subtitle = "中文源自@晓松故事会"

    for idx, cn, en in subtitles:
        output_path = os.path.join(frames_dir, f"frame_{idx:03d}.jpg")
        create_frame(title, subtitle, cn, en, output_path)
        if idx % 50 == 0:
            print(f"  已生成 {idx}/{len(subtitles)}")

    print(f"完成！所有图片保存在: {frames_dir}")
    conn.close()

except Exception as e:
    print(f"错误: {e}")
