#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用简单的concat文件列表方式拼接双语视频
"""

import os
import subprocess
import tempfile


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
    
    # 创建临时文件列表
    with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f:
        # 交替写入中文和英文视频路径
        for (ch_idx, ch_path), (en_idx, en_path) in zip(chinese_videos, english_videos):
            if ch_idx != en_idx:
                print(f"错误：视频索引不匹配！中文索引 {ch_idx}，英文索引 {en_idx}")
                return
            
            # 使用绝对路径
            ch_abs_path = os.path.abspath(ch_path).replace('\\', '/')
            en_abs_path = os.path.abspath(en_path).replace('\\', '/')
            
            f.write(f"file '{ch_abs_path}'\n")
            f.write(f"file '{en_abs_path}'\n")
        
        temp_file = f.name
    
    try:
        # 使用FFmpeg拼接视频
        cmd = [
            'ffmpeg', '-y',
            '-f', 'concat',
            '-safe', '0',
            '-i', temp_file,
            '-c', 'copy',
            output_file
        ]
        
        print("正在拼接前10句双语视频...")
        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)}")
    finally:
        # 清理临时文件
        if os.path.exists(temp_file):
            os.remove(temp_file)


if __name__ == "__main__":
    main()
