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

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


def get_srts_data(adid):
    """
    获取srts数据
    """
    db_path = r"\\ll\D\xtrssvjj\db\dpd.db"
    try:
        conn = sqlite3.connect(db_path)
        cur = conn.cursor()
        
        # 查询srts数据，按idx排序
        cur.execute("SELECT idx, cn, en FROM srts WHERE adid=? ORDER BY idx", (adid,))
        srtsdata = cur.fetchall()
        conn.close()
        
        print(f"找到 {len(srtsdata)} 条字幕数据")
        return srtsdata
    except Exception as e:
        print(f"获取srts数据错误: {e}")
        return []


def wrap_text(text, font, max_width):
    """
    自动换行函数
    """
    if not text:
        return []
    
    # 检测是否包含中文字符
    has_chinese = any('\u4e00' <= char <= '\u9fff' for char in text)
    
    if has_chinese:
        # 中文按字符分割
        lines = []
        current_line = ""
        for char in text:
            test_line = current_line + char
            bbox = font.getbbox(test_line)
            width = bbox[2] - bbox[0]
            if 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:
        # 英文按单词分割
        words = text.split()
        lines = []
        current_line = ""
        for word in words:
            test_line = current_line + " " + word if current_line else word
            bbox = font.getbbox(test_line)
            width = bbox[2] - bbox[0]
            if 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


def remove_trailing_punctuation(text):
    """
    去掉字幕最后的标点
    """
    if not text:
        return text
    
    # 去掉最后的逗号或句号
    if text.endswith(('，', '。', ',', '.')):
        text = text[:-1]
    
    return text


def create_subtitle_image(adname, author, idx, cn, en, output_path):
    """
    创建字幕图片
    """
    try:
        # 创建1080x1920的黑色背景图片
        img = Image.new('RGB', (1080, 1920), color='black')
        draw = ImageDraw.Draw(img)
        
        # 加载字体
        try:
            title_font = ImageFont.truetype("C:\\Windows\\Fonts\\msyh.ttc", 64)
            subtitle_font = ImageFont.truetype("C:\\Windows\\Fonts\\msyh.ttc", 52)
            cn_font = ImageFont.truetype("C:\\Windows\\Fonts\\msyh.ttc", 66)
            en_font = ImageFont.truetype("C:\\Windows\\Fonts\\arial.ttf", 72)
        except Exception as e:
            print(f"字体加载错误: {e}")
            return False
        
        # 去掉字幕最后的标点
        cn = remove_trailing_punctuation(cn)
        
        # 标题（adname）
        title = adname.replace('_', ' ')
        title_lines = wrap_text(title, title_font, 1000)
        title_y = 260
        
        for line in title_lines:
            draw.text((540, title_y), line, font=title_font, fill='white', anchor='mm')
            title_y += 84  # 64px字体 + 20px行间距
        
        # 副标题
        subtitle = f"译自@{author}"
        draw.text((540, title_y + 40), subtitle, font=subtitle_font, fill='white', anchor='mm')
        
        # 中文字幕
        cn_lines = wrap_text(cn, cn_font, 1000)
        cn_y = title_y + 40 + 92 + 200  # 副标题位置 + 52px字体 + 40px间距 + 200px间距
        
        for line in cn_lines:
            draw.text((540, cn_y), line, font=cn_font, fill='#FFD700', anchor='mm')
            cn_y += 86  # 66px字体 + 20px行间距
        
        # 英文字幕
        en_lines = wrap_text(en, en_font, 1000)
        en_y = cn_y + 40  # 中文字幕和英文字幕之间的间距
        
        for line in en_lines:
            draw.text((540, en_y), line, font=en_font, fill='white', anchor='mm')
            en_y += 92  # 72px字体 + 20px行间距
        
        # 保存图片
        img.save(output_path)
        return True
    except Exception as e:
        print(f"创建字幕图片错误: {e}")
        return False


def generate_subtitle_images(adid, adname, author, output_dir):
    """
    生成所有字幕图片
    """
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        print(f"创建输出目录: {output_dir}")
    
    # 获取字幕数据
    srtsdata = get_srts_data(adid)
    if not srtsdata:
        print("错误: 未找到字幕数据")
        return
    
    # 生成每张字幕图片
    for idx, cn, en in srtsdata:
        output_path = os.path.join(output_dir, f"vertical_subtitle_{idx:03d}.png")
        
        # 如果图片已存在，跳过
        if os.path.exists(output_path):
            print(f"字幕图片 {idx:03d} 已存在，跳过...")
            continue
        
        # 创建字幕图片
        print(f"正在生成字幕图片 {idx:03d}...")
        if create_subtitle_image(adname, author, idx, cn, en, output_path):
            print(f"  成功: {output_path}")
        else:
            print(f"  失败: vertical_subtitle_{idx:03d}.png")
    
    print(f"\n完成！字幕图片保存到: {output_dir}")


if __name__ == "__main__":
    adid = 8423
    adname = "韩寒创业简史_续集_伟大的父亲叫托举__韩寒__飞驰人生__人物传记__商业故事__掘金计划2026"
    author = "黄非红Nored"
    output_dir = "韩寒创业简史_续集_subtitle_images"
    
    print("开始生成字幕图片")
    print(f"adid: {adid}")
    print(f"adname: {adname}")
    print(f"author: {author}")
    print(f"输出目录: {output_dir}")
    
    generate_subtitle_images(adid, adname, author, output_dir)
