#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试简化版语速调整功能
"""

import os
import sys
import json

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

from core import _8_2_dub_chunks, _10_gen_audio

def main():
    print("🔧 测试简化版语速调整功能...")
    
    try:
        # 步骤1: 生成简化的配音块
        print("\n🎬 生成简化的配音块...")
        _8_2_dub_chunks.gen_dub_chunks()
        
        # 检查配音块配置
        with open('output/dub_chunks.json', 'r', encoding='utf-8') as f:
            chunks = json.load(f)
        
        print(f"✅ 生成了 {len(chunks)} 个独立音频片段")
        
        # 显示前几个片段的信息
        for i, chunk in enumerate(chunks[:3]):
            print(f"\n📋 片段 {chunk['task_id']}:")
            print(f"   文本: {chunk['text'][:50]}...")
            print(f"   原始时长: {chunk['duration']:.2f}s")
            print(f"   目标时长: {chunk['target_duration']:.2f}s")
            print(f"   切分标记: {chunk['cut_off']}")
        
        # 步骤2: 测试音频生成
        print(f"\n🚀 测试简化版音频生成...")
        _10_gen_audio.gen_audio()
        
        # 检查结果
        with open('output/dub_chunks.json', 'r', encoding='utf-8') as f:
            updated_chunks = json.load(f)
        
        print("\n📊 结果统计:")
        total = len(updated_chunks)
        processed = sum(1 for chunk in updated_chunks if 'final_duration' in chunk)
        perfect = sum(1 for chunk in updated_chunks if 'final_duration' in chunk and abs(chunk['final_duration'] - chunk['target_duration']) <= 0.1)
        good = sum(1 for chunk in updated_chunks if 'final_duration' in chunk and 0.1 < abs(chunk['final_duration'] - chunk['target_duration']) <= 0.3)
        
        print(f"   总片段: {total}")
        print(f"   已处理: {processed}")
        print(f"   完美匹配: {perfect}")
        print(f"   良好匹配: {good}")
        
        # 显示处理详情
        print("\n📋 处理详情:")
        for chunk in updated_chunks:
            if 'final_duration' in chunk:
                task_id = chunk['task_id']
                target = chunk['target_duration']
                final = chunk['final_duration']
                speed = chunk.get('speed_factor', 1.0)
                diff = final - target
                
                status = "✅" if abs(diff) <= 0.1 else "⚡" if abs(diff) <= 0.3 else "⚠️"
                print(f"   {status} 片段 {task_id}: {final:.2f}s (目标: {target:.2f}s, 差异: {diff:+.2f}s, 语速: {speed:.2f}x)")
        
        print("✅ 简化版音频生成测试完成！")
        return True
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    if success:
        print("\n🎉 简化版语速调整功能测试成功！")
    else:
        print("\n⚠️ 测试失败，需要进一步调试。")
