#!/usr/bin/env python3
"""
重新拼接视频 - 使用原始片段和静态视频交替拼接
"""
import os
import subprocess

from console_helper import safe_print, print_info


def concatenate_videos(video_files, output_file):
    """拼接视频"""
    if os.path.exists(output_file):
        os.remove(output_file)
    
    if not video_files:
        return False
    
    input_args = []
    for video in video_files:
        input_args.extend(['-i', video])
    
    n = len(video_files)
    input_labels = []
    for i in range(n):
        input_labels.append(f"[{i}:v][{i}:a]")
    
    filter_complex = ''.join(input_labels) + f"concat=n={n}:v=1:a=1[outv][outa]"
    
    args = [
        'ffmpeg',
        '-y'
    ] + input_args + [
        '-filter_complex', filter_complex,
        '-map', '[outv]',
        '-map', '[outa]',
        '-c:v', 'libx264',
        '-preset', 'fast',
        '-c:a', 'aac',
        '-ar', '44100',
        '-ac', '1',
        '-pix_fmt', 'yuv420p',
        '-movflags', '+faststart',
        output_file
    ]
    
    try:
        subprocess.run(args, check=True, capture_output=True)
        return True
    except:
        return False


def main():
    output_dir = "respect_video"
    segments_dir = os.path.join(output_dir, "segments")
    static_videos_dir = os.path.join(output_dir, "static_videos")
    
    safe_print("=" * 60)
    safe_print("重新拼接视频")
    safe_print("=" * 60)
    safe_print("")
    
    # 构建视频列表：原始片段和静态视频交替
    video_list = []
    
    # 获取所有片段和静态视频
    segment_files = sorted([f for f in os.listdir(segments_dir) if f.startswith('segment_') and f.endswith('.mp4')])
    static_video_files = sorted([f for f in os.listdir(static_videos_dir) if f.startswith('static_video_') and f.endswith('.mp4')])
    
    safe_print(f"找到 {len(segment_files)} 个原始片段")
    safe_print(f"找到 {len(static_video_files)} 个静态视频")
    safe_print("")
    
    # 交替拼接
    for i in range(1, 125):
        segment_file = os.path.join(segments_dir, f"segment_{i:03d}.mp4")
        static_video_file = os.path.join(static_videos_dir, f"static_video_{i:03d}.mp4")
        
        if os.path.exists(segment_file):
            video_list.append(segment_file)
        
        if os.path.exists(static_video_file):
            video_list.append(static_video_file)
    
    safe_print(f"拼接 {len(video_list)} 个视频文件...")
    safe_print("")
    
    output_file = os.path.join(output_dir, "final_video.mp4")
    if concatenate_videos(video_list, output_file):
        print_info("完成", f"最终视频: {output_file}")
        
        # 显示文件大小
        file_size = os.path.getsize(output_file) / (1024 * 1024)
        safe_print(f"文件大小: {file_size:.2f} MB")
    else:
        safe_print("拼接失败")
        return
    
    safe_print("=" * 60)
    safe_print("完成!")
    safe_print("=" * 60)


if __name__ == '__main__':
    main()
