#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用en字段生成TTS音频，然后与图片合并成视频片段
"""

import os
import sqlite3
import subprocess
import asyncio
import edge_tts


async def generate_tts_audio(text, output_file):
    """
    使用edge_tts生成TTS音频
    """
    try:
        communicate = edge_tts.Communicate(text, "en-US-AriaNeural", rate="-30%")
        await communicate.save(output_file)
        return True
    except Exception as e:
        print(f"  错误: TTS生成失败 - {e}")
        return False


def merge_image_tts_to_video(image_file, audio_file, output_file):
    """
    合并图片和TTS音频生成视频片段
    """
    cmd = [
        "ffmpeg", "-y",
        "-loop", "1",
        "-i", image_file,
        "-i", audio_file,
        "-c:v", "libx264",
        "-tune", "stillimage",
        "-c:a", "aac",
        "-b:a", "192k",
        "-pix_fmt", "yuv420p",
        "-shortest",
        output_file
    ]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
        return result.returncode == 0
    except Exception as e:
        print(f"  错误: {e}")
        return False


async def main():
    """
    主函数
    """
    # 连接数据库
    conn = sqlite3.connect('../srtsegjoin/dpd.db')
    cur = conn.cursor()
    
    # 查询所有字幕
    cur.execute('SELECT idx, en FROM srts WHERE adid=8397 ORDER BY idx')
    rows = cur.fetchall()
    
    print(f"找到 {len(rows)} 条字幕")
    
    # 创建输出目录
    tts_dir = "698_罗永浩的十字路口_tts"
    video_dir = "698_罗永浩的十字路口_tts_videos"
    
    if not os.path.exists(tts_dir):
        os.makedirs(tts_dir)
    
    if not os.path.exists(video_dir):
        os.makedirs(video_dir)
    
    # 处理每条字幕
    for idx, en in rows:
        # 去掉最后的标点
        if en and (en.endswith(',') or en.endswith('.')):
            en = en[:-1]
        
        print(f"处理 idx={idx}: {en[:50]}...")
        
        # TTS音频文件
        tts_file = os.path.join(tts_dir, f"tts_{idx:03d}.mp3")
        
        # 生成TTS音频
        if not await generate_tts_audio(en, tts_file):
            continue
        
        # 图片文件
        image_file = f"698_罗永浩的十字路口_vertical_images/vertical_subtitle_{idx:03d}.png"
        
        if not os.path.exists(image_file):
            print(f"  警告: 图片文件不存在 - {image_file}")
            continue
        
        # 视频文件
        video_file = os.path.join(video_dir, f"video_{idx:03d}.mp4")
        
        # 合并图片和TTS音频
        if merge_image_tts_to_video(image_file, tts_file, video_file):
            print(f"  生成视频: {video_file}")
        else:
            print(f"  错误: 生成视频失败")
    
    conn.close()
    print(f"\n完成！TTS音频保存到: {tts_dir}")
    print(f"视频片段保存到: {video_dir}")


if __name__ == "__main__":
    asyncio.run(main())
