#!/usr/bin/env python3
"""
重新生成"牛津大学AI"前10句字幕图片（正确的author：阳明门下0729）
"""
import sqlite3
from PIL import Image, ImageDraw, ImageFont
import os

db_path = "\\\\ll\\D\\xtrssvjj\\dpd.db"
output_dir = "oxford_frames_10"

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

conn = sqlite3.connect(db_path)
cursor = conn.cursor()

adid = 8237
cursor.execute("SELECT idx, cn, en FROM srts WHERE adid = ? ORDER BY idx LIMIT 10", (adid,))
subtitles = cursor.fetchall()

font_path = "C:/Windows/Fonts/simhei.ttf"
title_font = ImageFont.truetype(font_path, 64)  # 标题64px
subtitle_font = ImageFont.truetype(font_path, 52)  # 副标题52px
cn_font = ImageFont.truetype(font_path, 66)  # 中文66px
en_font = ImageFont.truetype(font_path, 66)  # 英文66px
title_text = "分享一个牛津大学的学生是如何使用AI的"
subtitle_text = "译自@阳明门下0729"  # 从author字段读取

def clean_punctuation(text):
    """去掉末尾的逗号或句号"""
    if text and text[-1] in ['，', '。', ',', '.']:
        return text[:-1]
    return text

def wrap_text(text, font, max_width, draw, is_english=False):
    """自动换行函数（英文单词完整换行）"""
    if not is_english:
        # 中文按字符换行
        lines = []
        current_line = ""
        for char in text:
            test_line = current_line + char
            bbox = draw.textbbox((0, 0), test_line, font=font)
            line_width = bbox[2] - bbox[0]
            if line_width <= max_width:
                current_line = test_line
            else:
                if current_line:
                    lines.append(current_line)
                current_line = char
        if current_line:
            lines.append(current_line)
        return lines
    else:
        # 英文按单词换行
        lines = []
        current_line = ""
        words = text.split()
        
        for word in words:
            test_line = current_line + (" " if current_line else "") + word
            bbox = draw.textbbox((0, 0), test_line, font=font)
            line_width = bbox[2] - bbox[0]
            
            if line_width <= max_width:
                current_line = test_line
            else:
                if current_line:
                    lines.append(current_line)
                current_line = word
        
        if current_line:
            lines.append(current_line)
        return lines

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

for idx, cn, en in subtitles:
    img = Image.new('RGB', (1080, 1920), color='black')
    draw = ImageDraw.Draw(img)
    
    max_text_width = 1000
    
    # 标题自动折行
    title_lines = wrap_text(title_text, title_font, max_text_width, draw)
    y_title = 260  # 标题下移四行
    for line in title_lines:
        bbox = draw.textbbox((0, 0), line, font=title_font)
        title_width = bbox[2] - bbox[0]
        x_title = (1080 - title_width) // 2
        draw.text((x_title, y_title), line, font=title_font, fill='white')
        y_title += bbox[3] - bbox[1] + 20  # 标题行间距20px
    
    bbox = draw.textbbox((0, 0), subtitle_text, font=subtitle_font)
    subtitle_width = bbox[2] - bbox[0]
    x_subtitle = (1080 - subtitle_width) // 2
    y_subtitle = y_title + 40  # 副标题与标题隔开一行
    draw.text((x_subtitle, y_subtitle), subtitle_text, font=subtitle_font, fill='white')
    
    y_text = y_subtitle + bbox[3] - bbox[1] + 40 + 5 * 40  # 副标题与字幕隔开五行
    
    cn_clean = clean_punctuation(cn)
    cn_lines = wrap_text(cn_clean, cn_font, max_text_width, draw)
    for line in cn_lines:
        bbox = draw.textbbox((0, 0), line, font=cn_font)
        cn_width = bbox[2] - bbox[0]
        x_cn = (1080 - cn_width) // 2
        draw.text((x_cn, y_text), line, font=cn_font, fill='#FFD700')  # 中文黄色
        y_text += bbox[3] - bbox[1] + 20  # 行间距20px
    
    y_text += 40
    
    en_clean = clean_punctuation(en)
    en_lines = wrap_text(en_clean, en_font, max_text_width, draw, is_english=True)
    for line in en_lines:
        bbox = draw.textbbox((0, 0), line, font=en_font)
        en_width = bbox[2] - bbox[0]
        x_en = (1080 - en_width) // 2
        draw.text((x_en, y_text), line, font=en_font, fill='white')  # 英文白色
        y_text += bbox[3] - bbox[1] + 20  # 行间距20px
    
    output_path = os.path.join(output_dir, f"frame_{idx:03d}.jpg")
    img.save(output_path)
    print(f"  已生成 {idx}/{len(subtitles)-1}")

print(f"\n完成！共生成 {len(subtitles)} 张图片")
print(f"副标题: {subtitle_text}")
print(f"保存路径: {output_dir}")

conn.close()
