#!/usr/bin/env python3
"""用第4句的帧图片生成第5句的带字幕图片"""
import os
import subprocess
import textwrap

# 导入编码处理模块
from console_helper import safe_print, print_header, print_info, print_done


def escape_text_for_ffmpeg(text):
    """为FFmpeg的drawtext滤镜转义文本"""
    escaped = text.replace("'", "'\\''")
    return escaped


def wrap_text(text, max_chars=35):
    """将长文本按指定字符数换行"""
    wrapped = textwrap.fill(text, width=max_chars)
    return wrapped


def add_subtitle_to_image(input_image, output_image, subtitle_text, ffmpeg_path="ffmpeg"):
    """为图片添加字幕"""
    # 处理字幕文本，自动换行
    wrapped_text = wrap_text(subtitle_text, max_chars=35)
    
    # 将文本按行分割
    lines = wrapped_text.split('\n')
    
    # 构建多个drawtext滤镜，每行一个
    filters = []
    y_position = 50  # 起始Y位置
    line_height = 60  # 每行高度（字体50 + 间距10）
    
    for i, line in enumerate(lines):
        # 转义特殊字符
        safe_line = escape_text_for_ffmpeg(line)
        current_y = y_position + i * line_height
        
        filter_str = (
            f"drawtext=text='{safe_line}':"
            f"fontsize=50:"
            f"fontcolor=yellow:"
            f"borderw=3:"
            f"bordercolor=red:"
            f"x=(w-text_w)/2:"
            f"y={current_y}"
        )
        filters.append(filter_str)
    
    # 组合所有滤镜
    vf_filter = ','.join(filters)
    
    args = [
        ffmpeg_path,
        '-y',
        '-i', input_image,
        '-vf', vf_filter,
        '-frames:v', '1',
        output_image
    ]
    
    try:
        subprocess.run(args, check=True, capture_output=True)
        return True
    except subprocess.CalledProcessError as e:
        safe_print(f"      添加字幕失败: {e}")
        return False


def main():
    print_header("用第4句帧图片生成第5句带字幕图片")
    
    # 第5句字幕文本
    subtitle_text = "Speaking of this field,"
    
    # 使用第4句的帧图片
    input_image = "all_frames/frame_004.jpg"
    output_image = "all_frames_with_subtitle/frame_005_with_subtitle.jpg"
    
    if not os.path.exists(input_image):
        safe_print(f"错误: 原始帧图片 {input_image} 不存在")
        return
    
    safe_print(f"使用第4句的帧图片: {input_image}")
    safe_print(f"字幕文本: '{subtitle_text}'")
    safe_print(f"输出到: {output_image}")
    safe_print("")
    
    if add_subtitle_to_image(input_image, output_image, subtitle_text):
        print_info("成功生成", output_image)
    else:
        safe_print("生成失败")
        return
    
    print_done()


if __name__ == '__main__':
    main()
