#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import sqlite3
import subprocess
import shutil


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 FROM srts 
        WHERE adid = ? 
        ORDER BY idx
    """, (adid,))
    
    subtitles = []
    for row in cursor.fetchall():
        idx, start, end, cn = row
        # 解析时间格式
        start_ms = int(start)
        end_ms = int(end)
        subtitles.append((idx, start_ms, end_ms, cn))
    
    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 split_audio(adid):
    """
    分割音频
    """
    # 配置
    db_path = r'\\ll\D\xtrssvjj\db\dpd.db'
    
    # 获取adname
    adname = get_adname(adid, db_path)
    print(f"adname: {adname}")
    
    # 音频文件路径
    audio_file = os.path.join(r'\\ll\D\xtrssvjj', f"{adname}.mp3")
    print(f"音频文件: {audio_file}")
    
    # 检查音频文件是否存在
    if not os.path.exists(audio_file):
        print(f"错误：音频文件不存在: {audio_file}")
        return False
    
    # 输出目录
    output_dir = f"{adname}_audio"
    
    # 清理输出目录
    if os.path.exists(output_dir):
        shutil.rmtree(output_dir)
    os.makedirs(output_dir)
    
    # 获取字幕
    subtitles = get_subtitles(adid, db_path)
    print(f"找到 {len(subtitles)} 句字幕")
    
    if not subtitles:
        print("错误：未找到字幕信息")
        return False
    
    # 分割音频
    for i in range(len(subtitles)):
        idx, start_ms, end_ms, cn = subtitles[i]
        
        # 计算分割时间
        if i == 0:
            # 第一句
            seg_start = start_ms
            if i < len(subtitles) - 1:
                next_start = subtitles[i+1][1]
                seg_end = (end_ms + next_start) // 2
            else:
                seg_end = end_ms + 1000
        elif i == len(subtitles) - 1:
            # 最后一句
            prev_end = subtitles[i-1][2]
            seg_start = (prev_end + start_ms) // 2
            seg_end = end_ms + 1000
        else:
            # 中间句
            prev_end = subtitles[i-1][2]
            next_start = subtitles[i+1][1]
            seg_start = (prev_end + start_ms) // 2
            seg_end = (end_ms + next_start) // 2
        
        # 计算间隔
        if i == 0:
            prev_gap = 0
        else:
            prev_gap = start_ms - subtitles[i-1][2]
        
        if i == len(subtitles) - 1:
            next_gap = 0
        else:
            next_gap = subtitles[i+1][1] - end_ms
        
        # 计算字幕时长
        subtitle_duration = end_ms - start_ms
        
        # 计算音频片段理论时长
        audio_segment_duration = seg_end - seg_start
        
        # 前后修正标记
        header_fixed = 'v' if prev_gap < 800 else 'x'
        tail_fixed = 'v' if next_gap < 800 else 'x'
        
        # 转换为秒
        start_sec = seg_start / 1000
        duration_sec = audio_segment_duration / 1000
        
        # 输出文件名
        output_path = os.path.join(output_dir, f"seg{idx:03d}.mp3")
        
        # 执行分割
        cmd = [
            "ffmpeg", "-y",
            "-ss", str(start_sec),
            "-t", str(duration_sec),
            "-i", audio_file,
            "-acodec", "libmp3lame",
            "-ar", "44100",
            "-ac", "2",
            output_path
        ]
        
        subprocess.run(cmd, capture_output=True)
        
        # 获取实际音频长度
        actual_duration = get_file_duration(output_path)
        
        # 重命名文件
        new_filename = f"seg{idx:03d}-{header_fixed}-{prev_gap}-{subtitle_duration}-{audio_segment_duration}-{actual_duration}-{next_gap}-{tail_fixed}.mp3"
        new_path = os.path.join(output_dir, new_filename)
        
        # 处理文件重命名冲突
        if os.path.exists(new_path):
            os.remove(new_path)
        os.rename(output_path, new_path)
        
        # 显示进度
        if (i + 1) % 10 == 0:
            print(f"分割音频 {i+1}/{len(subtitles)}")
    
    print(f"完成！分割了 {len(subtitles)} 个音频片段")
    print(f"输出目录: {output_dir}")
    return True


def main():
    """
    主函数
    """
    if len(sys.argv) != 2:
        print("用法: python cnsplit.py <adid>")
        print("示例: python cnsplit.py 8442")
        sys.exit(1)
    
    try:
        adid = int(sys.argv[1])
    except ValueError:
        print("错误：adid必须是数字")
        sys.exit(1)
    
    print(f"=== 音频分割工具 ===")
    print(f"adid: {adid}")
    
    success = split_audio(adid)
    
    if success:
        print("\n分割完成！")
    else:
        print("\n分割失败！")
        sys.exit(1)


if __name__ == "__main__":
    main()