#!/usr/bin/env python3
"""
只拼接第五句的视频片段
直接使用现有的文件，不重新生成
"""
import os
import subprocess

# 导入编码处理模块
from console_helper import (
    safe_print, print_header, print_step, print_info,
    print_success, print_fail, print_done
)


def concatenate_videos(video_list, output_path, ffmpeg_path="ffmpeg"):
    """拼接多个视频"""
    list_file = 'concat_list.txt'
    with open(list_file, 'w', encoding='utf-8') as f:
        for video in video_list:
            escaped_path = video.replace('\\', '/')
            f.write(f"file '{escaped_path}'\n")
    
    args = [
        ffmpeg_path,
        '-y',
        '-f', 'concat',
        '-safe', '0',
        '-i', list_file,
        '-c:v', 'libx264',
        '-c:a', 'aac',
        '-ar', '44100',
        '-ac', '1',
        '-pix_fmt', 'yuv420p',
        output_path
    ]
    
    try:
        subprocess.run(args, check=True, capture_output=True)
        os.remove(list_file)
        return True
    except subprocess.CalledProcessError as e:
        safe_print(f"      拼接视频失败: {e}")
        try:
            os.remove(list_file)
        except:
            pass
        return False


def main():
    # 配置
    segment_file = "all_segments/segment_005.mp4"
    static_video_file = "all_static_videos_with_silence/static_video_005.mp4"
    output_video = "only_line5.mp4"
    
    print_header("只拼接第五句视频")
    safe_print(f"原始片段: {segment_file}")
    safe_print(f"静态视频: {static_video_file}")
    safe_print(f"输出视频: {output_video}")
    safe_print("")
    
    # 检查文件是否存在
    if not os.path.exists(segment_file):
        safe_print(f"错误: 原始片段文件 {segment_file} 不存在")
        return
    
    if not os.path.exists(static_video_file):
        safe_print(f"错误: 静态视频文件 {static_video_file} 不存在")
        return
    
    # 构建视频列表
    video_list = [segment_file, static_video_file]
    
    print_info("视频数", str(len(video_list)))
    safe_print("开始拼接...")
    
    if concatenate_videos(video_list, output_video):
        print_info("成功生成", output_video)
    else:
        safe_print("拼接视频失败")
        return
    
    print_done()


if __name__ == '__main__':
    main()
