#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用重新编码方式拼接双语视频，确保音频采样率一致
"""

import os
import subprocess
import tempfile


def get_video_files(video_dir):
    """
    获取所有视频文件列表
    """
    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)))
    
    video_files.sort(key=lambda x: x[0])
    return video_files


def main():
    chinese_video_dir = "Artemis_II_十天绕月_videos"
    english_video_dir = "Artemis_II_十天绕月_tts_videos"
    output_file = "Artemis_II_十天绕月_bilingual.mp4"
    
    chinese_videos = get_video_files(chinese_video_dir)
    english_videos = get_video_files(english_video_dir)
    
    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:
        cmd = [
            'ffmpeg', '-y',
            '-f', 'concat',
            '-safe', '0',
            '-i', temp_file,
            '-c:v', 'libx264',
            '-c:a', 'aac',
            '-ar', '44100',
            '-b:a', '192k',
            '-pix_fmt', 'yuv420p',
            output_file
        ]
        
        print("正在拼接完整的双语视频（重新编码）...")
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
        
        if result.returncode == 0:
            print(f"成功！完整的双语视频保存到: {output_file}")
            if os.path.exists(output_file):
                file_size = os.path.getsize(output_file)
                print(f"文件大小: {file_size / 1024 / 1024:.2f} MB")
        else:
            print(f"错误：拼接失败 - {result.stderr}")
    finally:
        if os.path.exists(temp_file):
            os.remove(temp_file)


if __name__ == "__main__":
    main()
