#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
为"韩寒创业简史 上"生成字幕图片
"""

import os
import sqlite3
from PIL import Image, ImageDraw, ImageFont
import re


def is_chinese_char(char):
    """
    检查字符是否为中文字符
    """
    return '\u4e00' <= char <= '\u9fff'


def wrap_text(text, max_width, font):
    """
    自动换行文本
    """
    lines = []
    current_line = []
    current_width = 0
    
    # 检查是否包含中文字符
    has_chinese = any(is_chinese_char(c) for c in text)
    
    if has_chinese:
        # 中文按字符分割
        for char in text:
            char_width = font.getbbox(char)[2] - font.getbbox(char)[0]
            if current_width + char_width <= max_width:
                current_line.append(char)
                current_width += char_width
            else:
                lines.append(''.join(current_line))
                current_line = [char]
                current_width = char_width
    else:
        # 英文按单词分割
        words = text.split()
        for word in words:
            word_width = font.getbbox(word)[2] - font.getbbox(word)[0]
            space_width = font.getbbox(' ')[2] - font.getbbox(' ')[0]
            
            if current_line:
                if current_width + space_width + word_width <= max_width:
                    current_line.append(' ')
                    current_line.append(word)
                    current_width += space_width + word_width
                else:
                    lines.append(' '.join(current_line))
                    current_line = [word]
                    current_width = word_width
            else:
                current_line.append(word)
                current_width = word_width
    
    if current_line:
        lines.append(''.join(current_line))
    
    return lines


def generate_subtitle_images(adid, adname, author):
    """
    生成字幕图片
    """
    # 获取srts数据
    db_path = r"\\ll\\d\\xtrssvjj\\dpd.db"
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()
    
    cur.execute("SELECT idx, cn, en FROM srts WHERE adid=? AND cn IS NOT NULL AND cn != '' ORDER BY idx", (adid,))
    srtsdata = cur.fetchall()
    conn.close()
    
    # 创建输出目录
    output_dir = f"{adname}_images"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 配置字体（使用Windows系统默认字体）
    try:
        title_font = ImageFont.truetype("simsun.ttc", 64)
        subtitle_font = ImageFont.truetype("simsun.ttc", 52)
        cn_font = ImageFont.truetype("simsun.ttc", 66)
        en_font = ImageFont.truetype("arial.ttf", 72)
    except:
        # 回退到默认字体
        title_font = ImageFont.load_default()
        subtitle_font = ImageFont.load_default()
        cn_font = ImageFont.load_default()
        en_font = ImageFont.load_default()
    
    # 背景尺寸
    width, height = 1080, 1920
    
    for idx, cn, en in srtsdata:
        # 去掉字幕最后的标点
        if cn.endswith('，') or cn.endswith('。'):
            cn = cn[:-1]
        if en and (en.endswith(',') or en.endswith('.')):
            en = en[:-1]
        
        # 创建背景
        image = Image.new('RGB', (width, height), (0, 0, 0))
        draw = ImageDraw.Draw(image)
        
        # 绘制标题（下移四行，从100px移到260px）
        title = adname
        title_lines = wrap_text(title, 1000, title_font)
        title_y = 260
        for line in title_lines:
            line_width = title_font.getbbox(line)[2] - title_font.getbbox(line)[0]
            x = (width - line_width) // 2
            draw.text((x, title_y), line, font=title_font, fill=(255, 255, 255))
            title_y += 80  # 标题行间距
        
        # 绘制副标题（与标题隔开一行，40px）
        subtitle = f"译自@{author}"
        subtitle_width = subtitle_font.getbbox(subtitle)[2] - subtitle_font.getbbox(subtitle)[0]
        x = (width - subtitle_width) // 2
        draw.text((x, title_y + 40), subtitle, font=subtitle_font, fill=(255, 255, 255))
        
        # 绘制中文字幕（与副标题隔开五行，200px）
        cn_y = title_y + 40 + 200
        cn_lines = wrap_text(cn, 1000, cn_font)
        for line in cn_lines:
            line_width = cn_font.getbbox(line)[2] - cn_font.getbbox(line)[0]
            x = (width - line_width) // 2
            draw.text((x, cn_y), line, font=cn_font, fill=(255, 215, 0))  # 黄色
            cn_y += 86  # 行间距
        
        # 绘制英文字幕（与中文字幕隔开一行，40px）
        if en:
            en_y = cn_y + 40
            en_lines = wrap_text(en, 1000, en_font)
            for line in en_lines:
                line_width = en_font.getbbox(line)[2] - en_font.getbbox(line)[0]
                x = (width - line_width) // 2
                draw.text((x, en_y), line, font=en_font, fill=(255, 255, 255))
                en_y += 92  # 行间距
        
        # 保存图片
        output_path = os.path.join(output_dir, f"vertical_subtitle_{idx:03d}.png")
        image.save(output_path)
        print(f"生成图片: {output_path}")
    
    print(f"\n完成！共生成 {len(srtsdata)} 张图片")


if __name__ == "__main__":
    adid = 8428  # 韩寒创业简史 上
    adname = "韩寒创业简史_上集_以笔为矛的少年天才__韩寒__飞驰人生__人物传记__商业故事__掘金计划2026"
    author = "黄非红Nored"
    generate_subtitle_images(adid, adname, author)
