#!/usr/bin/env python3
"""调试第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)
    
    safe_print(f"原始文本: '{subtitle_text}'")
    safe_print(f"换行后文本: '{wrapped_text}'")
    
    # 将文本按行分割
    lines = wrapped_text.split('\n')
    safe_print(f"行数: {len(lines)}")
    
    # 构建多个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
        
        safe_print(f"  第{i+1}行: '{safe_line}' (y={current_y})")
        
        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)
    safe_print(f"滤镜: {vf_filter}")
    
    args = [
        ffmpeg_path,
        '-y',
        '-i', input_image,
        '-vf', vf_filter,
        '-frames:v', '1',
        output_image
    ]
    
    safe_print(f"执行命令: {' '.join(args)}")
    
    try:
        result = subprocess.run(args, check=True, capture_output=True, text=True)
        safe_print("命令执行成功")
        return True
    except subprocess.CalledProcessError as e:
        safe_print(f"添加字幕失败")
        if e.stderr:
            safe_print(f"错误信息: {e.stderr}")
        return False


def main():
    print_header("调试第5句字幕生成")
    
    # 第5句字幕文本
    subtitle_text = "Speaking of this field,"
    
    input_image = "all_frames/frame_005.jpg"
    output_image = "all_frames_with_subtitle/frame_005_with_subtitle_debug.jpg"
    
    if not os.path.exists(input_image):
        safe_print(f"错误: 原始帧图片 {input_image} 不存在")
        return
    
    safe_print(f"输入图片: {input_image}")
    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()
