#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
计算每句双语的时间：addstart + cn音频 + addend + en音频
用法: python calculate_bilingual_time.py <adid>
"""

import os
import sys
import sqlite3
import subprocess
import glob


def get_file_duration(file_path):
    """
    获取音频文件时长（毫秒）
    """
    cmd = ["ffprobe", "-v", "quiet", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file_path]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode == 0:
        return int(float(result.stdout.strip()) * 1000)
    return 0


def get_subtitles(adid, db_path):
    """
    从数据库获取字幕信息
    """
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    cursor.execute("""
        SELECT idx, start, end, cn, en FROM srts 
        WHERE adid = ? 
        ORDER BY idx
    """, (adid,))
    
    subtitles = []
    for row in cursor.fetchall():
        idx, start, end, cn, en = row
        # 解析时间格式
        start_ms = int(start)
        end_ms = int(end)
        subtitles.append((idx, start_ms, end_ms, cn, en))
    
    conn.close()
    return subtitles


def get_adname(adid, db_path):
    """
    从数据库获取adname
    """
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    cursor.execute("SELECT DISTINCT adname FROM srts WHERE adid = ? LIMIT 1", (adid,))
    result = cursor.fetchone()
    conn.close()
    
    if result:
        return result[0]
    return f"adid_{adid}"


def calculate_bilingual_time(adid):
    """
    计算每句双语的时间
    """
    # 配置
    db_path = r'\\ll\D\xtrssvjj\db\dpd.db'
    
    # 获取adname
    adname = get_adname(adid, db_path)
    print(f"adname: {adname}")
    
    # 目录路径
    cn_audio_dir = f"{adname}_cn_audio"
    en_tts_dir = os.path.join(r'\\ll\D\xtrssvjj', 'tts', adname)
    
    # 检查目录是否存在
    if not os.path.exists(cn_audio_dir):
        print(f"错误：中文音频目录不存在: {cn_audio_dir}")
        return False
    
    if not os.path.exists(en_tts_dir):
        print(f"错误：英文TTS目录不存在: {en_tts_dir}")
        return False
    
    # 获取字幕
    subtitles = get_subtitles(adid, db_path)
    print(f"找到 {len(subtitles)} 句字幕")
    
    if not subtitles:
        print("错误：未找到字幕信息")
        return False
    
    # 音频文件路径
    audio_file = os.path.join(r'\\ll\D\xtrssvjj', f"{adname}.mp3")
    
    # 获取音频文件总长度
    audio_duration = get_file_duration(audio_file)
    print(f"音频总长度: {audio_duration} 毫秒")
    
    # 计算每句的startpos、endpos、addstart、addend
    enhanced_subtitles = []
    for i, (idx, start, end, cn, en) in enumerate(subtitles):
        prevend = subtitles[i-1][2] if i > 0 else 0
        startgap = start - prevend if i > 0 else 0
        
        if i < len(subtitles)-1:
            nextstart = subtitles[i+1][1]
            endgap = nextstart - end
        else:
            # 最后一句的nextstart为音频文件的实际总长度
            nextstart = audio_duration
            endgap = nextstart - end if audio_duration > end else 0
        
        # 计算startpos和endpos
        # 第一句的startpos固定为0
        if i == 0:
            startpos = 0
        else:
            startpos = (prevend + start) // 2
        
        # 最后一句的endpos为视频的最后位置(总长度-1)
        if i == len(subtitles)-1:
            endpos = audio_duration - 1
        else:
            endpos = (end + nextstart) // 2
        
        # 计算addstart值：第一句addstart=0，后面的用400-(start-startpos)
        if i == 0:
            addstart = 0
        else:
            addstart = 400 - (start - startpos)
            if addstart <= 0:
                addstart = 0
        
        # 计算addend值：最后一句addend=0，其他用400-(endpos-end)
        if i == len(subtitles)-1:
            addend = 0
        else:
            addend = 400 - (endpos - end)
            if addend <= 0:
                addend = 0
        
        # 获取中文音频长度
        cn_audio_file = os.path.join(cn_audio_dir, f"seg{idx:03d}-{startpos}-{endpos}-*.mp3")
        cn_files = glob.glob(cn_audio_file)
        cn_duration = 0
        if cn_files:
            cn_duration = get_file_duration(cn_files[0])
        
        # 获取英文TTS长度 - 只使用网络共享位置的TTS文件
        en_tts_pattern = os.path.join(en_tts_dir, f"*-{idx:04d}.mp3")
        en_files = glob.glob(en_tts_pattern)
        
        en_duration = 0
        if en_files:
            # 打印使用的网络TTS文件路径
            print(f"使用网络TTS文件: {en_files[0]}")
            # 计算调整语速后的TTS长度（原长度 / 0.7）
            original_duration = get_file_duration(en_files[0])
            en_duration = original_duration / 0.7
        
        # 计算双语总时间
        bilingual_time = addstart + cn_duration + addend + en_duration
        
        enhanced_subtitles.append((idx, start, end, startpos, endpos, addstart, addend, cn_duration, en_duration, bilingual_time, cn, en))
    
    # 生成HTML表格
    html_file = f"bilingual_time_{adid}.html"
    generate_html(enhanced_subtitles, adid, adname, html_file)
    
    # 计算总时间
    total_time = sum(sub[9] for sub in enhanced_subtitles)
    print(f"总双语时间: {total_time} 毫秒")
    print(f"生成的HTML文件: {html_file}")
    
    return True

def generate_html(subtitles, adid, adname, output_file):
    """
    生成HTML表格显示双语时间信息
    """
    html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>双语时间计算 - adid {adid}</title>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #333;
            font-size: 18px;
            margin-bottom: 20px;
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
        }}
        th, td {{
            padding: 6px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }}
        th {{
            background-color: #f2f2f2;
            font-weight: bold;
        }}
        .monospace {{
            font-family: monospace;
        }}
        .cn-content {{
            max-width: 300px;
            word-wrap: break-word;
        }}
        .highlight-time {{
            font-weight: bold;
            color: #0066cc;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>adid: {adid} | 视频标题: {adname} | 字幕数量: {len(subtitles)} 句</h1>
        <table>
            <tr>
                <th>序号</th>
                <th>start</th>
                <th>end</th>
                <th>startpos</th>
                <th>endpos</th>
                <th>addstart</th>
                <th>cn音频</th>
                <th>addend</th>
                <th>en音频</th>
                <th>双语总时间</th>
                <th>中文内容</th>
                <th>英文内容</th>
            </tr>
"""
    
    for idx, start, end, startpos, endpos, addstart, addend, cn_duration, en_duration, bilingual_time, cn, en in subtitles:
        html_content += f"""
            <tr>
                <td>{idx}</td>
                <td class="monospace">{start}</td>
                <td class="monospace">{end}</td>
                <td class="monospace">{startpos}</td>
                <td class="monospace">{endpos}</td>
                <td class="monospace">{addstart}</td>
                <td class="monospace">{cn_duration}</td>
                <td class="monospace">{addend}</td>
                <td class="monospace">{en_duration}</td>
                <td class="monospace highlight-time">{bilingual_time}</td>
                <td class="cn-content">{cn}</td>
                <td class="cn-content">{en}</td>
            </tr>
"""
    
    html_content += """
        </table>
    </div>
</body>
</html>
"""
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_content)


def main():
    """
    主函数
    """
    if len(sys.argv) != 2:
        print("用法: python calculate_bilingual_time.py <adid>")
        print("示例: python calculate_bilingual_time.py 8496")
        sys.exit(1)
    
    try:
        adid = int(sys.argv[1])
    except ValueError:
        print("错误：adid必须是数字")
        sys.exit(1)
    
    print(f"=== 双语时间计算工具 ===")
    print(f"adid: {adid}")
    
    success = calculate_bilingual_time(adid)
    
    if success:
        print("\n计算完成！")
    else:
        print("\n计算失败！")
        sys.exit(1)


if __name__ == "__main__":
    main()
