#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
为"韩寒创业简史 上"生成TTS视频片段
"""

import os
import subprocess
import re


def create_video_segment(image_path, audio_path, output_path):
    """
    使用FFmpeg将图片和音频合并为视频片段
    """
    cmd = [
        'ffmpeg', '-y',
        '-loop', '1',
        '-i', image_path,
        '-i', audio_path,
        '-c:v', 'libx264',
        '-tune', 'stillimage',
        '-c:a', 'aac',
        '-b:a', '192k',
        '-pix_fmt', 'yuv420p',
        '-shortest',
        output_path
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
    return result.returncode == 0


def main():
    # 配置路径
    adname = "韩寒创业简史_上集_以笔为矛的少年天才__韩寒__飞驰人生__人物传记__商业故事__掘金计划2026"
    image_dir = f"{adname}_images"
    tts_dir = f"{adname}_tts"
    output_dir = f"{adname}_tts_videos"
    
    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 获取TTS音频文件
    tts_files = []
    for filename in os.listdir(tts_dir):
        if filename.endswith('.mp3') and filename.startswith('tts_'):
            match = re.match(r'tts_(\d+)\.mp3', filename)
            if match:
                idx = int(match.group(1))
                tts_files.append((idx, os.path.join(tts_dir, filename)))
    
    tts_files.sort(key=lambda x: x[0])
    print(f"找到 {len(tts_files)} 个TTS音频文件")
    
    # 合并每个片段
    for idx, audio_path in tts_files:
        # 构建图片路径
        image_path = os.path.join(image_dir, f"vertical_subtitle_{idx:03d}.png")
        
        # 检查图片是否存在
        if not os.path.exists(image_path):
            print(f"  警告: 图片不存在 - {image_path}")
            continue
        
        # 构建输出路径
        output_path = os.path.join(output_dir, f"video_{idx:03d}.mp4")
        
        # 强制重新生成所有视频文件
        # if os.path.exists(output_path):
        #     print(f"TTS视频片段 {idx:03d} 已存在，跳过...")
        #     continue
        
        # 创建视频片段
        print(f"正在生成TTS视频片段 {idx:03d}...")
        if create_video_segment(image_path, audio_path, output_path):
            print(f"  成功: {output_path}")
        else:
            print(f"  失败: video_{idx:03d}.mp4")
    
    print(f"\n完成！TTS视频片段保存到: {output_dir}")


if __name__ == "__main__":
    main()
