#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试语速调整功能的脚本
验证配音块生成和音频语速调整的完整流程
"""

import os
import sys
import json
from pathlib import Path

# 设置路径
current_dir = os.path.dirname(os.path.abspath(__file__))
os.environ['PATH'] += os.pathsep + current_dir
sys.path.append(current_dir)

# 导入核心模块
from core.utils.config_utils import load_key, update_key
from core import _8_2_dub_chunks, _10_gen_audio

def create_test_translate_result():
    """创建测试用的翻译结果数据"""
    test_data = [
        {
            "id": 1,
            "start": 0.0,
            "end": 3.5,
            "original_text": "Hello, how are you today?",
            "translated_text": "你好，你今天怎么样？"
        },
        {
            "id": 2,
            "start": 4.0,
            "end": 7.2,
            "original_text": "I'm doing great, thank you for asking.",
            "translated_text": "我很好，谢谢你的询问。"
        },
        {
            "id": 3,
            "start": 8.0,
            "end": 12.5,
            "original_text": "Would you like to have lunch together today?",
            "translated_text": "你想今天一起吃午餐吗？"
        }
    ]
    
    # 确保output目录存在
    os.makedirs('output', exist_ok=True)
    
    # 保存测试数据
    with open('output/translate_result.json', 'w', encoding='utf-8') as f:
        json.dump(test_data, f, ensure_ascii=False, indent=2)
    
    print("✅ 创建了测试翻译数据")

def test_dub_chunks_generation():
    """测试配音块生成功能"""
    print("\n🎬 测试配音块生成...")
    
    try:
        # 创建测试数据
        create_test_translate_result()
        
        # 生成配音块
        _8_2_dub_chunks.gen_dub_chunks()
        
        # 检查结果
        if os.path.exists('output/dub_chunks.json'):
            with open('output/dub_chunks.json', 'r', encoding='utf-8') as f:
                chunks = json.load(f)
            
            print(f"✅ 成功生成 {len(chunks)} 个配音块")
            
            # 显示一些统计信息
            cutoff_count = sum(1 for chunk in chunks if chunk['cut_off'] == 1)
            speed_issues = sum(1 for chunk in chunks if chunk['speed_status'] > 0)
            
            print(f"📊 切分点数量: {cutoff_count}")
            print(f"⚡ 需要语速调整的片段: {speed_issues}")
            
            # 显示第一个块的详细信息
            if chunks:
                first_chunk = chunks[0]
                print(f"\n📋 第一个块的信息:")
                print(f"   文本: {first_chunk['text']}")
                print(f"   时长: {first_chunk['duration']:.2f}s")
                print(f"   估算时长: {first_chunk['est_dur']:.2f}s")
                print(f"   语速状态: {first_chunk['speed_status']}")
            
            return True
        else:
            print("❌ 配音块文件未生成")
            return False
            
    except Exception as e:
        print(f"❌ 配音块生成失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_speed_adjustment_logic():
    """测试语速调整逻辑"""
    print("\n⚡ 测试语速调整逻辑...")
    
    try:
        # 模拟一些测试数据
        test_chunks = [
            {
                'real_dur': 3.0,   # 实际TTS时长
                'tol_dur': 3.5,    # 容忍时长
                'duration': 3.2,   # 原始时长
                'gap': 0.5,        # 间隙
                'tolerance': 0.3   # 容忍度
            },
            {
                'real_dur': 2.8,
                'tol_dur': 3.0,
                'duration': 2.5,
                'gap': 0.8,
                'tolerance': 0.5
            }
        ]
        
        # 测试速度因子计算
        from core._10_gen_audio import calculate_chunk_speed_factor
        
        accept = load_key("speed_factor.accept") if load_key("speed_factor.accept") else 1.3
        min_speed = load_key("speed_factor.min") if load_key("speed_factor.min") else 0.8
        
        speed_factor, keep_gaps = calculate_chunk_speed_factor(test_chunks, accept, min_speed)
        
        print(f"✅ 计算出的语速因子: {speed_factor}")
        print(f"✅ 是否保留间隙: {keep_gaps}")
        
        # 验证结果合理性
        if 0.5 <= speed_factor <= 2.0:
            print("✅ 语速因子在合理范围内")
            return True
        else:
            print("⚠️ 语速因子超出预期范围")
            return False
            
    except Exception as e:
        print(f"❌ 语速调整逻辑测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """主测试函数"""
    print("🧪 开始测试语速调整功能...")
    
    # 设置一些基本配置
    update_key("tolerance", 0.5)
    update_key("speed_factor.accept", 1.3)
    update_key("speed_factor.min", 0.8)
    
    success_count = 0
    total_tests = 2
    
    # 测试1: 配音块生成
    if test_dub_chunks_generation():
        success_count += 1
    
    # 测试2: 语速调整逻辑
    if test_speed_adjustment_logic():
        success_count += 1
    
    # 总结
    print(f"\n📊 测试结果: {success_count}/{total_tests} 个测试通过")
    
    if success_count == total_tests:
        print("🎉 所有测试通过！语速调整功能实现正确。")
        return True
    else:
        print("⚠️ 部分测试失败，请检查实现。")
        return False

if __name__ == "__main__":
    main()

