#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
为"韩寒创业简史 上"拼接双语视频
"""

import os
import subprocess
import re


def get_video_files(video_dir):
    """
    获取视频文件列表，按索引排序
    """
    video_files = []
    for filename in os.listdir(video_dir):
        if filename.endswith('.mp4') and filename.startswith('video_'):
            match = re.match(r'video_(\d+)\.mp4', filename)
            if match:
                idx = int(match.group(1))
                video_files.append((idx, os.path.join(video_dir, filename)))
    
    # 按索引排序
    video_files.sort(key=lambda x: x[0])
    return video_files


def combine_bilingual_videos(chinese_videos, tts_videos, output_file):
    """
    拼接双语视频（中文+英文交替）
    """
    # 确保两个视频列表长度相同
    if len(chinese_videos) != len(tts_videos):
        print(f"视频数量不匹配：中文 {len(chinese_videos)}，英文 {len(tts_videos)}")
        return False
    
    total_videos = len(chinese_videos)
    print(f"开始拼接双语视频，共 {total_videos} 对视频")
    
    # 分批处理，每批10对视频
    batch_size = 10
    temp_files = []
    
    for i in range(0, total_videos, batch_size):
        batch_end = min(i + batch_size, total_videos)
        batch_videos = []
        
        # 构建批次视频列表（中文+英文交替）
        for j in range(i, batch_end):
            chinese_idx, chinese_path = chinese_videos[j]
            tts_idx, tts_path = tts_videos[j]
            
            if chinese_idx == tts_idx:
                batch_videos.append(chinese_path)
                batch_videos.append(tts_path)
            else:
                print(f"索引不匹配：中文 {chinese_idx}，英文 {tts_idx}")
                return False
        
        # 生成批次输出文件名
        batch_output = f"temp_batch_{i//batch_size}.mp4"
        temp_files.append(batch_output)
        
        # 构建FFmpeg命令（使用filter_complex统一音频格式）
        inputs = []
        filters = []
        
        for k, video_path in enumerate(batch_videos):
            inputs.extend(['-i', video_path])
            filters.append(f"[{k}:v][{k}:a]")
        
        filter_complex = ''.join(filters) + f"concat=n={len(batch_videos)}:v=1:a=1[outv][outa]"
        
        cmd = [
            'ffmpeg', '-y'
        ] + inputs + [
            '-filter_complex', filter_complex,
            '-map', '[outv]',
            '-map', '[outa]',
            '-c:v', 'libx264',
            '-c:a', 'aac',
            '-b:a', '192k',
            batch_output
        ]
        
        print(f"处理批次 {i//batch_size + 1}/{(total_videos + batch_size - 1)//batch_size}...")
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
        
        if result.returncode != 0:
            print(f"  失败: {result.stderr}")
            return False
        else:
            print(f"  成功: {batch_output}")
    
    # 合并所有批次
    if len(temp_files) > 1:
        print("合并所有批次...")
        merge_inputs = []
        merge_filters = []
        
        for k, temp_file in enumerate(temp_files):
            merge_inputs.extend(['-i', temp_file])
            merge_filters.append(f"[{k}:v][{k}:a]")
        
        merge_filter_complex = ''.join(merge_filters) + f"concat=n={len(temp_files)}:v=1:a=1[outv][outa]"
        
        cmd = [
            'ffmpeg', '-y'
        ] + merge_inputs + [
            '-filter_complex', merge_filter_complex,
            '-map', '[outv]',
            '-map', '[outa]',
            '-c:v', 'libx264',
            '-c:a', 'aac',
            '-b:a', '192k',
            output_file
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
        
        if result.returncode != 0:
            print(f"  失败: {result.stderr}")
            return False
        else:
            print(f"  成功: {output_file}")
        
        # 清理临时文件
        for temp_file in temp_files:
            if os.path.exists(temp_file):
                os.remove(temp_file)
    else:
        # 只有一个批次，直接重命名
        os.rename(temp_files[0], output_file)
        print(f"  成功: {output_file}")
    
    return True


def main():
    # 配置路径
    adname = "韩寒创业简史_上集_以笔为矛的少年天才__韩寒__飞驰人生__人物传记__商业故事__掘金计划2026"
    chinese_dir = f"{adname}_videos"
    tts_dir = f"{adname}_tts_videos"
    output_file = f"{adname}_bilingual.mp4"
    
    # 获取视频文件
    chinese_videos = get_video_files(chinese_dir)
    tts_videos = get_video_files(tts_dir)
    
    print(f"找到 {len(chinese_videos)} 个中文视频文件")
    print(f"找到 {len(tts_videos)} 个英文TTS视频文件")
    
    # 拼接双语视频
    if combine_bilingual_videos(chinese_videos, tts_videos, output_file):
        print(f"\n完成！双语视频保存到: {output_file}")
    else:
        print("\n拼接失败！")


if __name__ == "__main__":
    main()
