#!/usr/bin/env python3
"""
生成所有字幕图片（432句）
"""
import sqlite3
import os
from PIL import Image, ImageDraw, ImageFont

db_path = "\\\\ll\\D\\xtrssvjj\\dpd.db"
frames_dir = "shitu_frames"
if not os.path.exists(frames_dir):
    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, 54)
subtitle_font = ImageFont.truetype(font_path, 36)
cn_font = ImageFont.truetype(font_path, 60)
en_font = ImageFont.truetype(font_path, 60)

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)

    # 标题（白色）
    title_bbox = draw.textbbox((0, 0), title, font=title_font)
    title_width = title_bbox[2] - title_bbox[0]
    draw.text(((width - title_width) // 2, 160), title, font=title_font, fill='white')

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

    # 中文（黄色，自动换行）
    max_width = width - 100
    cn_lines = wrap_text(cn_text, cn_font, max_width)
    y_offset = 700
    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 += 90

    # 英文（白色，自动换行）
    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 += 90

    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 = 8281 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}")
