#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
为每句字幕生成静态图片
包含中英文双字幕，中文66px黄色，英文72px白色
英文单词完整换行，副标题格式"译自@author"
"""

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


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


def get_author(adname):
    """
    从author数据库获取作者信息
    """
    author_db_path = r"\\ll\\d\\wxvddata\\dpd.db"
    try:
        conn = sqlite3.connect(author_db_path)
        cur = conn.cursor()
        
        # 使用adname的前60个字符进行模糊匹配
        search_name = adname[:60]
        cur.execute("SELECT author FROM ads WHERE name LIKE ?", (f"%{search_name}%",))
        result = cur.fetchone()
        conn.close()
        
        return result[0] if result else "未知"
    except Exception as e:
        print(f"获取author失败: {e}")
        return "未知"


def get_full_adname(adid):
    """
    从主数据库获取完整的adname
    """
    main_db_path = r"\\ll\\d\\xtrssvjj\\dpd.db"
    try:
        conn = sqlite3.connect(main_db_path)
        cur = conn.cursor()
        
        cur.execute("SELECT adname FROM srts WHERE adid=? LIMIT 1", (adid,))
        result = cur.fetchone()
        conn.close()
        
        return result[0] if result else f"unknown_{adid}"
    except Exception as e:
        print(f"获取adname失败: {e}")
        return f"unknown_{adid}"


def generate_subtitle_images(adid):
    """
    为指定adid的字幕生成静态图片
    """
    # 获取完整的adname
    adname = get_full_adname(adid)
    print(f"使用完整adname: {adname}")
    
    # 获取author信息
    author = get_author(adname)
    print(f"获取到author: {author}")
    
    # 连接主数据库
    main_db_path = r"\\ll\\d\\xtrssvjj\\dpd.db"
    conn = sqlite3.connect(main_db_path)
    cur = conn.cursor()
    
    # 查询字幕数据
    cur.execute('SELECT idx, cn, en, start, end FROM srts WHERE adid=? ORDER BY idx', (adid,))
    srtsdata = cur.fetchall()
    conn.close()
    
    if not srtsdata:
        print(f"未找到adid={adid}的字幕数据")
        return
    
    # 创建输出目录
    output_dir = f"{adname}_images"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    print(f"开始生成图片，共 {len(srtsdata)} 句...")
    
    # 加载字体
    try:
        # 尝试使用系统字体
        chinese_font = ImageFont.truetype("simhei.ttf", 66)
        english_font = ImageFont.truetype("arial.ttf", 72)
        subtitle_font = ImageFont.truetype("simhei.ttf", 52)  # 副标题52px
    except Exception as e:
        # 如果系统字体不可用，使用默认字体
        print(f"加载字体失败: {e}")
        chinese_font = ImageFont.load_default()
        english_font = ImageFont.load_default()
        subtitle_font = ImageFont.load_default()
    
    # 图片尺寸（竖屏）
    width = 1080
    height = 1920
    
    for row in srtsdata:
        idx, cn, en, start, end = row
        
        # 创建黑色背景图片
        image = Image.new('RGB', (width, height), color='black')
        draw = ImageDraw.Draw(image)
        
        # 计算文本位置
        padding = 100
        max_text_width = width - 2 * padding
        
        # 绘制标题（adname）
        title_font = ImageFont.truetype("simhei.ttf", 64) if 'simhei.ttf' in str(chinese_font) else chinese_font
        title_lines = wrap_text(adname, max_text_width, title_font)
        title_total_height = len(title_lines) * 80
        title_start_y = 260  # 标题位置：下移四行
        
        for i, line in enumerate(title_lines):
            text_width = draw.textbbox((0, 0), line, font=title_font)[2]
            x = (width - text_width) // 2
            y = title_start_y + i * 80
            draw.text((x, y), line, font=title_font, fill='#FFFFFF')  # 白色
        
        # 绘制副标题
        subtitle = f"译自@{author}"
        subtitle_width = draw.textbbox((0, 0), subtitle, font=subtitle_font)[2]
        x = (width - subtitle_width) // 2
        y = title_start_y + title_total_height + 40  # 副标题与标题间距：隔开一行(40px)
        draw.text((x, y), subtitle, font=subtitle_font, fill='#FFFFFF')  # 白色
        
        # 绘制中文
        if cn:
            cn_lines = wrap_text(cn, max_text_width, chinese_font)
            cn_total_height = len(cn_lines) * 80  # 行高
            cn_start_y = y + 40 + 200  # 副标题与字幕间距：隔开五行(200px)
            
            for i, line in enumerate(cn_lines):
                text_width = draw.textbbox((0, 0), line, font=chinese_font)[2]
                x = (width - text_width) // 2
                y_cn = cn_start_y + i * 80
                draw.text((x, y_cn), line, font=chinese_font, fill='#FFD700')  # 黄色
        
        # 绘制英文
        if en:
            en_lines = wrap_text(en, max_text_width, english_font)
            en_total_height = len(en_lines) * 90  # 行高
            en_start_y = cn_start_y + cn_total_height + 40  # 中英文间距
            
            for i, line in enumerate(en_lines):
                text_width = draw.textbbox((0, 0), line, font=english_font)[2]
                x = (width - text_width) // 2
                y_en = en_start_y + i * 90
                draw.text((x, y_en), line, font=english_font, fill='#FFFFFF')  # 白色
        
        # 保存图片
        output_file = os.path.join(output_dir, f"vertical_subtitle_{idx:03d}.png")
        image.save(output_file)
        print(f"  生成图片: {output_file}")
    
    print(f"\n完成！图片保存到: {output_dir}")


if __name__ == "__main__":
    # 使用"我们需要知识分子吗_思考"的adid
    adid = 8407
    generate_subtitle_images(adid)
