#!/usr/bin/env python3
"""
将原始视频片段和静态视频按顺序拼接成一个总视频
顺序: segment_01.mp4 -> static_video_001.mp4 -> segment_02.mp4 -> static_video_002.mp4 -> ...
"""
import os
import subprocess

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


def get_video_duration(video_path):
    """获取视频时长"""
    args = [
        'ffprobe',
        '-v', 'quiet',
        '-print_format', 'json',
        '-show_format',
        video_path
    ]
    
    try:
        result = subprocess.run(args, check=True, capture_output=True, text=True)
        import json
        data = json.loads(result.stdout)
        return float(data['format']['duration'])
    except Exception as e:
        safe_print(f"      获取视频时长失败: {e}")
        return 0


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:
        result = subprocess.run(args, check=True, capture_output=True, text=True)
        os.remove(list_file)
        return True
    except subprocess.CalledProcessError as e:
        safe_print(f"      拼接视频失败")
        if e.stderr:
            error_msg = e.stderr
            safe_print(f"      错误信息: {error_msg[:300]}")
        try:
            os.remove(list_file)
        except:
            pass
        return False


def main():
    # 配置
    original_segments = [
        "segment_01.mp4",
        "segment_02.mp4",
        "segment_03.mp4",
        "segment_04.mp4"
    ]
    static_videos_dir = "static_videos_with_silence"
    output_video = "combined_video.mp4"
    
    print_header("拼接视频")
    safe_print("拼接顺序:")
    safe_print("  原始片段1 -> 静态视频1 -> 原始片段2 -> 静态视频2 -> ...")
    safe_print("")
    
    # 构建视频列表（交替拼接）
    video_list = []
    
    print_step(1, 2, "构建视频列表...")
    for i in range(1, 5):  # 前4句
        # 原始视频片段
        original = original_segments[i-1]
        if os.path.exists(original):
            video_list.append(original)
            print_info(f"  添加", f"原始片段: {original}")
        else:
            safe_print(f"  警告: 原始片段 {original} 不存在")
        
        # 静态视频
        static_video = os.path.join(static_videos_dir, f"static_video_{i:03d}.mp4")
        if os.path.exists(static_video):
            video_list.append(static_video)
            print_info(f"  添加", f"静态视频: {static_video}")
        else:
            safe_print(f"  警告: 静态视频 {static_video} 不存在")
    
    if not video_list:
        safe_print("错误: 没有找到任何视频文件")
        return
    
    print_info("总视频数", str(len(video_list)))
    safe_print("")
    
    # 拼接视频
    print_step(2, 2, "拼接视频...")
    if concatenate_videos(video_list, output_video):
        duration = get_video_duration(output_video)
        print_info("成功生成", output_video)
        print_info("总时长", f"{duration:.2f}秒 ({duration/60:.2f}分钟)")
    else:
        safe_print("拼接视频失败")
        return
    
    print_done()


if __name__ == '__main__':
    main()
