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

# 数据库路径
db_path = "\\\\ll\\D\\xtrssvjj\\dpd.db"

# 输出目录
output_dir = "shitu_frames"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 创建黑色背景图片 (720x1280)
width, height = 720, 1280

# 尝试使用系统中文字体
font_paths = [
    "C:/Windows/Fonts/msyh.ttc",      # 微软雅黑
    "C:/Windows/Fonts/simhei.ttf",    # 黑体
    "C:/Windows/Fonts/simsun.ttc",    # 宋体
]

title_font = None
subtitle_font = None
cn_font = None
en_font = None

for font_path in font_paths:
    if os.path.exists(font_path):
        try:
            title_font = ImageFont.truetype(font_path, 42)
            subtitle_font = ImageFont.truetype(font_path, 28)
            cn_font = ImageFont.truetype(font_path, 40)
            en_font = ImageFont.truetype(font_path, 30)
            print(f"使用字体: {font_path}")
            break
        except:
            continue

if title_font is None:
    print("未找到中文字体，使用默认字体")
    title_font = ImageFont.load_default()
    subtitle_font = ImageFont.load_default()
    cn_font = ImageFont.load_default()
    en_font = ImageFont.load_default()

# 固定文字内容
title = "师徒一场_张雪峰走好_上"
subtitle = "源自：@梁老师的故事汇"

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 draw_multiline_text(draw, text, font, fill, x, y, max_width, align='center'):
    """绘制多行文本"""
    lines = wrap_text(text, font, max_width)
    line_height = font.size + 10
    
    for i, line in enumerate(lines):
        bbox = font.getbbox(line)
        text_width = bbox[2] - bbox[0]
        
        if align == 'center':
            line_x = x - text_width // 2
        else:
            line_x = x
        
        draw.text((line_x, y + i * line_height), line, font=font, fill=fill)
    
    return len(lines) * line_height

# 查询所有字幕
try:
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    cursor.execute("SELECT idx, cn, en FROM srts WHERE adid = 8281 ORDER BY idx ASC")
    results = cursor.fetchall()
    
    print(f"找到 {len(results)} 条字幕")
    
    for idx, cn, en in results:
        # 创建新图片
        img = Image.new('RGB', (width, height), color='black')
        draw = ImageDraw.Draw(img)
        
        # 标题位置
        title_bbox = draw.textbbox((0, 0), title, font=title_font)
        title_width = title_bbox[2] - title_bbox[0]
        title_x = (width - title_width) // 2
        title_y = 150
        
        # 副标题位置
        subtitle_bbox = draw.textbbox((0, 0), subtitle, font=subtitle_font)
        subtitle_width = subtitle_bbox[2] - subtitle_bbox[0]
        subtitle_x = (width - subtitle_width) // 2
        subtitle_y = 220
        
        # 绘制标题和副标题
        draw.text((title_x, title_y), title, font=title_font, fill='white')
        draw.text((subtitle_x, subtitle_y), subtitle, font=subtitle_font, fill='gray')
        
        # 计算字幕起始位置（垂直居中）
        cn_lines = wrap_text(cn, cn_font, width - 80)
        en_lines = wrap_text(en, en_font, width - 80)
        
        total_lines = len(cn_lines) + len(en_lines)
        cn_line_height = cn_font.size + 10
        en_line_height = en_font.size + 10
        total_height = len(cn_lines) * cn_line_height + len(en_lines) * en_line_height + 20
        
        start_y = (height - total_height) // 2
        
        # 绘制中文字幕
        cn_y = start_y
        draw_multiline_text(draw, cn, cn_font, 'yellow', width // 2, cn_y, width - 80, 'center')
        
        # 绘制英文字幕
        en_y = start_y + len(cn_lines) * cn_line_height + 20
        draw_multiline_text(draw, en, en_font, 'white', width // 2, en_y, width - 80, 'center')
        
        # 保存图片
        output_path = os.path.join(output_dir, f"frame_{idx:03d}.jpg")
        img.save(output_path, quality=95)
        
        if (idx + 1) % 50 == 0:
            print(f"已生成 {idx + 1} 张图片")
    
    conn.close()
    
    print(f"完成！共生成 {len(results)} 张图片")
    print(f"图片保存在: {output_dir}")
    
except Exception as e:
    print(f"错误: {e}")
