#!/usr/bin/env python3
"""
测试降级到 0.1.3 版本是否解决了 QdrantVectorStore 问题
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from loguru import logger
from unittest.mock import Mock, patch

def test_downgraded_version():
    """测试降级后的版本"""
    print("=== 测试降级到 llama-index-vector-stores-qdrant 0.1.3 ===")
    
    # 1. 检查版本
    import llama_index.vector_stores.qdrant
    print(f"1. 当前版本: {llama_index.vector_stores.qdrant.__version__}")
    
    # 2. 测试创建 QdrantVectorStore 实例
    print("\n2. 测试创建 QdrantVectorStore 实例...")
    try:
        from llama_index.vector_stores.qdrant import QdrantVectorStore
        
        # 创建一个模拟的 QdrantClient
        mock_client = Mock()
        mock_client.get_collection = Mock(return_value=Mock())
        
        with patch('qdrant_client.QdrantClient', return_value=mock_client):
            with patch('qdrant_client.AsyncQdrantClient', return_value=Mock()):
                # 尝试创建实例
                store = QdrantVectorStore(
                    collection_name="test_collection",
                    client=mock_client,
                    enable_hybrid=False
                )
                
                print("✅ 成功创建 QdrantVectorStore 实例！")
                print(f"   集合名称: {store.collection_name}")
                print(f"   enable_hybrid: {store.enable_hybrid}")
                
                # 检查实例属性
                if hasattr(store, 'path'):
                    print(f"   path 字段值: {store.path}")
                
                return True
                
    except Exception as e:
        print(f"❌ 创建实例失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_with_patch_disabled():
    """测试禁用补丁的情况"""
    print("\n=== 测试禁用补丁的情况 ===")
    
    # 临时禁用补丁
    import src.utils.patches
    original_patch = src.utils.patches.patch_qdrant_vector_store
    
    def disabled_patch():
        print("补丁被禁用（跳过）")
        from llama_index.vector_stores.qdrant import QdrantVectorStore
        return QdrantVectorStore
    
    src.utils.patches.patch_qdrant_vector_store = disabled_patch
    
    try:
        # 重新导入以应用禁用补丁
        import importlib
        importlib.reload(llama_index.vector_stores.qdrant)
        
        from llama_index.vector_stores.qdrant import QdrantVectorStore
        
        mock_client = Mock()
        mock_client.get_collection = Mock(return_value=Mock())
        
        with patch('qdrant_client.QdrantClient', return_value=mock_client):
            with patch('qdrant_client.AsyncQdrantClient', return_value=Mock()):
                store = QdrantVectorStore(
                    collection_name="test_collection",
                    client=mock_client,
                    enable_hybrid=False
                )
                
                print("✅ 禁用补丁后也能成功创建实例（版本 0.1.3 没有 bug）")
                return True
                
    except Exception as e:
        print(f"❌ 禁用补丁后失败: {e}")
        return False
    finally:
        # 恢复原始补丁
        src.utils.patches.patch_qdrant_vector_store = original_patch

if __name__ == "__main__":
    print("测试降级解决方案")
    print("=" * 60)
    
    # 运行测试
    test1_success = test_downgraded_version()
    test2_success = test_with_patch_disabled()
    
    print("\n" + "=" * 60)
    print("测试结果总结:")
    print(f"  测试1（降级版本）: {'✅ 通过' if test1_success else '❌ 失败'}")
    print(f"  测试2（禁用补丁）: {'✅ 通过' if test2_success else '❌ 失败'}")
    
    if test1_success and test2_success:
        print("\n🎉 降级到 0.1.3 版本成功解决了 QdrantVectorStore Pydantic 验证问题！")
        print("\n建议：")
        print("  1. 可以移除或禁用 src/utils/patches.py 中的补丁")
        print("  2. 运行索引构建测试验证完整功能")
        sys.exit(0)
    else:
        print("\n❌ 降级测试失败，需要进一步调试。")
        sys.exit(1)