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

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


def wrap_text(text, font, max_width):
    """
    自动换行文本
    """
    lines = []
    current_line = []
    current_width = 0
    
    # 检测是否包含中文字符
    has_chinese = any(0x4e00 <= ord(c) <= 0x9fff for c in text)
    
    if has_chinese:
        # 中文按字符分割
        for char in text:
            bbox = font.getbbox(char)
            char_width = bbox[2] - bbox[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()
        bbox_space = font.getbbox(' ')
        space_width = bbox_space[2] - bbox_space[0]
        
        for word in words:
            bbox_word = font.getbbox(word)
            word_width = bbox_word[2] - bbox_word[0]
            
            if current_line:
                if current_width + space_width + word_width <= max_width:
                    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:
        if has_chinese:
            lines.append(''.join(current_line))
        else:
            lines.append(' '.join(current_line))
    
    return lines


def generate_subtitle_images(adid, author):
    """
    生成字幕图片
    """
    db_path = r'\\ll\D\xtrssvjj\db\dpd.db'
    output_dir = f"韩寒创业简史_下集_images"
    
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        print(f"创建输出目录: {output_dir}")
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 查询字幕
        cursor.execute("SELECT idx, cn, en FROM srts WHERE adid = ? ORDER BY idx", (adid,))
        subtitles = cursor.fetchall()
        
        print(f"找到 {len(subtitles)} 句字幕")
        
        # 字体设置
        title_font = ImageFont.truetype("simsun.ttc", 64)
        subtitle_font = ImageFont.truetype("simsun.ttc", 52)
        chinese_font = ImageFont.truetype("simsun.ttc", 66)
        english_font = ImageFont.truetype("arial.ttf", 72)
        
        # 标题和副标题
        title = "韩寒创业简史 下集 以光为媒的青春图腾"
        subtitle = f"译自@{author}"
        
        for idx, cn, en in subtitles:
            # 去掉最后的标点
            if cn.endswith('。') or cn.endswith('，'):
                cn = cn[:-1]
            if en.endswith('.') or en.endswith(','):
                en = en[:-1]
            
            # 创建图片
            image = Image.new('RGB', (1080, 1920), color='black')
            draw = ImageDraw.Draw(image)
            
            # 绘制标题
            title_lines = wrap_text(title, title_font, 1000)
            title_y = 260
            for line in title_lines:
                bbox = title_font.getbbox(line)
                line_width = bbox[2] - bbox[0]
                draw.text(
                    ((1080 - line_width) // 2, title_y),
                    line,
                    font=title_font,
                    fill='white'
                )
                title_y += 80
            
            # 绘制副标题
            bbox_sub = subtitle_font.getbbox(subtitle)
            subtitle_width = bbox_sub[2] - bbox_sub[0]
            draw.text(
                ((1080 - subtitle_width) // 2, title_y + 40),
                subtitle,
                font=subtitle_font,
                fill='white'
            )
            
            # 绘制中文字幕
            cn_lines = wrap_text(cn, chinese_font, 1000)
            cn_y = title_y + 240
            for line in cn_lines:
                bbox_cn = chinese_font.getbbox(line)
                line_width = bbox_cn[2] - bbox_cn[0]
                draw.text(
                    ((1080 - line_width) // 2, cn_y),
                    line,
                    font=chinese_font,
                    fill='#FFD700'
                )
                cn_y += 86
            
            # 绘制英文字幕
            en_lines = wrap_text(en, english_font, 1000)
            en_y = cn_y + 80
            for line in en_lines:
                bbox_en = english_font.getbbox(line)
                line_width = bbox_en[2] - bbox_en[0]
                draw.text(
                    ((1080 - line_width) // 2, en_y),
                    line,
                    font=english_font,
                    fill='white'
                )
                en_y += 92
            
            # 保存图片
            output_path = os.path.join(output_dir, f"subtitle_{idx:03d}.png")
            image.save(output_path)
            
            if (idx + 1) % 10 == 0:
                print(f"生成字幕图片 {idx + 1}/{len(subtitles)}")
        
        print(f"完成！生成了 {len(subtitles)} 张字幕图片")
        
    except Exception as e:
        print(f"错误: {e}")
    finally:
        if 'conn' in locals():
            conn.close()


if __name__ == "__main__":
    adid = 8434
    author = "黄非红Nored"
    generate_subtitle_images(adid, author)