#!/usr/bin/env python3
"""
测试脚本：验证解释器关闭时的竞态条件修复
"""
import threading
import time
import sys

def test_lazy_initialization():
    """测试 QMDRuntime 的延迟初始化"""
    print("✅ 测试 1: QMDRuntime 延迟初始化")
    
    from core.config import CONFIG
    from core.runtimes.qmd_runtime import QMDRuntime
    
    # 创建 QMDRuntime 实例（不应该立即初始化 ChromaDB）
    runtime = QMDRuntime(CONFIG)
    print("  ✓ QMDRuntime 实例创建成功（未初始化 ChromaDB）")
    
    # 验证 _initialized 标志
    assert not runtime._initialized, "应该延迟初始化"
    print("  ✓ 延迟初始化标志正确")
    
    return runtime

def test_background_thread_cleanup():
    """测试后台线程清理时的竞态条件"""
    print("\n✅ 测试 2: 后台线程清理（模拟 watch remove）")
    
    def background_task():
        """模拟后台清理任务"""
        time.sleep(0.1)  # 模拟一些工作
        try:
            from core.factories import initialize_system
            context_manager = initialize_system()
            print("  ✓ 后台线程成功初始化系统")
        except RuntimeError as e:
            if "cannot schedule new futures after interpreter shutdown" in str(e):
                print(f"  ✗ 捕获到竞态条件错误: {e}")
                raise
            raise
    
    # 启动守护线程
    thread = threading.Thread(target=background_task, daemon=True, name="TestCleanup")
    thread.start()
    
    # 给线程一点时间完成初始化
    time.sleep(0.5)
    print("  ✓ 后台线程启动成功（守护线程）")

def test_ensure_initialized():
    """测试 _ensure_initialized 方法"""
    print("\n✅ 测试 3: _ensure_initialized 延迟初始化")
    
    from core.config import CONFIG
    from core.runtimes.qmd_runtime import QMDRuntime
    
    runtime = QMDRuntime(CONFIG)
    assert not runtime._initialized
    
    # 第一次调用应该初始化
    runtime._ensure_initialized()
    assert runtime._initialized
    print("  ✓ 第一次调用 _ensure_initialized 成功")
    
    # 第二次调用应该跳过初始化
    runtime._ensure_initialized()
    assert runtime._initialized
    print("  ✓ 第二次调用 _ensure_initialized 跳过初始化")

if __name__ == "__main__":
    try:
        test_lazy_initialization()
        test_background_thread_cleanup()
        test_ensure_initialized()
        
        print("\n" + "="*50)
        print("✅ 所有测试通过！")
        print("="*50)
        sys.exit(0)
    except Exception as e:
        print(f"\n❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
