#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
只拼接前十句的双语视频，用于测试
"""

import os
import subprocess


def get_video_files(video_dir, max_count=10):
    """
    获取视频文件列表，最多取前max_count个
    """
    video_files = []
    for filename in os.listdir(video_dir):
        if filename.endswith('.mp4') and filename.startswith('video_'):
            # 解析文件名获取索引
            idx = int(filename.split('_')[1].split('.')[0])
            video_files.append((idx, os.path.join(video_dir, filename)))
    
    # 按索引排序并取前max_count个
    video_files.sort(key=lambda x: x[0])
    return video_files[:max_count]


def main():
    # 配置路径
    chinese_video_dir = "Artemis_II_十天绕月_videos"
    english_video_dir = "Artemis_II_十天绕月_tts_videos"
    output_file = "Artemis_II_十天绕月_bilingual_first_10.mp4"
    
    # 获取前10个视频文件
    chinese_videos = get_video_files(chinese_video_dir, 10)
    english_videos = get_video_files(english_video_dir, 10)
    
    print(f"找到 {len(chinese_videos)} 个中文视频片段")
    print(f"找到 {len(english_videos)} 个英文TTS视频片段")
    
    # 检查视频数量是否匹配
    if len(chinese_videos) != len(english_videos):
        print("错误：中文视频和英文TTS视频数量不匹配！")
        return
    
    # 构建FFmpeg命令
    input_args = []
    filter_complex = []
    
    # 收集所有输入文件
    for i, ((ch_idx, ch_path), (en_idx, en_path)) in enumerate(zip(chinese_videos, english_videos)):
        if ch_idx != en_idx:
            print(f"错误：视频索引不匹配！中文索引 {ch_idx}，英文索引 {en_idx}")
            return
        
        # 添加输入文件
        input_args.extend(['-i', ch_path])
        input_args.extend(['-i', en_path])
    
    # 构建filter_complex
    num_segments = len(chinese_videos)
    
    # 所有视频输入
    video_inputs = []
    for i in range(num_segments * 2):
        video_inputs.append(f'[{i}:v]')
    
    # 拼接所有视频
    filter_complex.append(''.join(video_inputs) + f'concat=n={num_segments * 2}:v=1:a=1[outv][outa]')
    
    # 构建完整命令
    cmd = [
        'ffmpeg', '-y'
    ] + input_args + [
        '-filter_complex', ';'.join(filter_complex),
        '-map', '[outv]',
        '-map', '[outa]',
        '-c:v', 'libx264',
        '-c:a', 'aac',
        '-b:a', '192k',
        output_file
    ]
    
    print("正在拼接前10句双语视频...")
    print(f"总视频片段数: {num_segments * 2}")
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
        
        if result.returncode == 0:
            print(f"成功！前10句双语视频保存到: {output_file}")
            # 检查文件大小
            if os.path.exists(output_file):
                file_size = os.path.getsize(output_file)
                print(f"文件大小: {file_size} 字节")
        else:
            print(f"错误：拼接失败 - {result.stderr}")
            # 打印完整命令以便调试
            print(f"命令: {' '.join(cmd)}")
    except Exception as e:
        print(f"执行错误: {e}")


if __name__ == "__main__":
    main()
