#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
直接拼接韩寒创业简史 下集的双语视频片段
"""

import os
import subprocess
import glob


def get_video_files(video_dir):
    """
    获取视频文件列表，按序号排序
    """
    pattern = os.path.join(video_dir, "video_*.mp4")
    files = glob.glob(pattern)
    
    # 提取序号并排序
    video_files = []
    for file in files:
        filename = os.path.basename(file)
        # 提取序号，格式为 video_{idx:03d}.mp4
        try:
            idx = int(filename.split('_')[1].split('.')[0])
            video_files.append((idx, file))
        except:
            continue
    
    # 按序号排序
    video_files.sort(key=lambda x: x[0])
    return video_files


def combine_batch(videos, batch_num, output_dir):
    """
    合并一批视频
    """
    if not videos:
        return None
    
    # 构建filter_complex参数
    filter_complex = ""
    input_args = []
    input_index = 0
    
    # 添加视频
    for i, (idx, path) in enumerate(videos):
        input_args.extend(["-i", path])
        filter_complex += f"[{input_index}:0][{input_index}:1]"
        input_index += 1
    
    # 统一音频格式并拼接
    num_videos = len(videos)
    filter_complex += f"concat=n={num_videos}:v=1:a=1[outv][outa]"
    
    # 输出文件
    output_path = os.path.join(output_dir, f"batch_{batch_num:03d}.mp4")
    
    # 构建FFmpeg命令
    cmd = [
        "ffmpeg", "-y"
    ] + input_args + [
        "-filter_complex", filter_complex,
        "-map", "[outv]",
        "-map", "[outa]",
        "-c:v", "libx264",
        "-c:a", "aac",
        "-b:a", "192k",
        output_path
    ]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
        if result.returncode == 0:
            print(f"  批次 {batch_num} 成功: {output_path}")
            return output_path
        else:
            print(f"  批次 {batch_num} 失败: {result.stderr}")
            return None
    except Exception as e:
        print(f"  批次 {batch_num} 错误: {e}")
        return None


def combine_all_videos(video_dir, output_dir, batch_size=10):
    """
    合并所有视频
    """
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        print(f"创建输出目录: {output_dir}")
    
    # 获取视频文件
    videos = get_video_files(video_dir)
    
    print(f"找到 {len(videos)} 个视频片段")
    
    # 分批处理
    total_batches = (len(videos) + batch_size - 1) // batch_size
    batch_files = []
    
    for batch_num in range(total_batches):
        start_idx = batch_num * batch_size
        end_idx = min(start_idx + batch_size, len(videos))
        
        # 获取当前批次的视频
        batch_videos = videos[start_idx:end_idx]
        
        print(f"正在处理批次 {batch_num + 1}/{total_batches} ({len(batch_videos)} 个视频)...")
        
        # 合并当前批次
        batch_file = combine_batch(batch_videos, batch_num, output_dir)
        if batch_file:
            batch_files.append(batch_file)
    
    if not batch_files:
        print("错误: 没有成功生成任何批次")
        return
    
    # 合并所有批次
    print(f"\n正在合并所有批次 ({len(batch_files)} 个批次)...")
    
    # 构建concat文件列表
    concat_file = os.path.join(output_dir, "concat_list.txt")
    with open(concat_file, "w", encoding='utf-8') as f:
        for batch_file in batch_files:
            # 使用绝对路径，并处理路径中的特殊字符
            abs_path = os.path.abspath(batch_file).replace("\\", "/")
            f.write(f"file '{abs_path}'\n")
    
    # 合并所有批次 - 直接输出到根目录
    final_output = "韩寒创业简史_下集_以光为媒的青春图腾__韩寒__飞驰人生__人物传记__商业故事__掘金计划2026_bilingual.mp4"
    
    cmd = [
        "ffmpeg", "-y",
        "-f", "concat",
        "-safe", "0",
        "-i", concat_file,
        "-c", "copy",
        final_output
    ]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
        if result.returncode == 0:
            print(f"成功: {final_output}")
            
            # 获取文件大小
            file_size = os.path.getsize(final_output) / (1024 * 1024)
            print(f"文件大小: {file_size:.2f} MB")
            
            # 清理批次文件
            for batch_file in batch_files:
                if os.path.exists(batch_file):
                    os.remove(batch_file)
            
            # 清理concat文件
            if os.path.exists(concat_file):
                os.remove(concat_file)
            
            print(f"\n完成！双语视频保存到: {final_output}")
        else:
            print(f"错误: {result.stderr}")
    except Exception as e:
        print(f"错误: {e}")


if __name__ == "__main__":
    video_dir = "韩寒创业简史_下集_videos"
    output_dir = "韩寒创业简史_下集_bilingual_output"
    
    print("开始拼接双语视频")
    print(f"视频目录: {video_dir}")
    print(f"输出目录: {output_dir}")
    
    combine_all_videos(video_dir, output_dir)
