#!/usr/bin/env python3
"""
验证 QdrantVectorStore 补丁是否解决了 Pydantic 验证问题
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

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

def test_patch_solves_pydantic_validation():
    """测试补丁是否解决了 Pydantic 验证问题"""
    print("=== 验证 QdrantVectorStore 补丁修复 ===")
    
    # 模拟 QdrantClient，避免网络连接
    mock_client = Mock()
    mock_client.get_collection = Mock(side_effect=Exception("模拟连接错误"))
    
    # 1. 首先测试未应用补丁的情况
    print("1. 测试未应用补丁的情况...")
    try:
        from llama_index.vector_stores.qdrant import QdrantVectorStore as OriginalQdrantVectorStore
        
        # 尝试创建实例（应该会失败）
        store = OriginalQdrantVectorStore(
            collection_name="test_collection",
            client=mock_client,
            enable_hybrid=False
        )
        print("❌ 未应用补丁时应该失败，但成功了（可能环境不同）")
        return False
    except Exception as e:
        error_msg = str(e)
        if "path" in error_msg.lower() and "required" in error_msg.lower():
            print(f"✅ 未应用补丁时按预期失败: {error_msg[:100]}...")
        else:
            print(f"⚠️  未应用补丁时失败，但不是因为 path 验证: {error_msg[:100]}...")
    
    # 2. 应用补丁并测试
    print("\n2. 应用补丁并测试...")
    try:
        # 应用补丁
        from src.utils.patches import patch_qdrant_vector_store
        patch_qdrant_vector_store()
        
        # 重新导入应用补丁后的类
        from llama_index.vector_stores.qdrant import QdrantVectorStore as PatchedQdrantVectorStore
        
        # 尝试创建实例
        store = PatchedQdrantVectorStore(
            collection_name="test_collection",
            client=mock_client,
            enable_hybrid=False
        )
        
        print("✅ 应用补丁后成功创建 QdrantVectorStore 实例！")
        print(f"   集合名称: {store.collection_name}")
        print(f"   path 字段值: {store.path}")
        print(f"   enable_hybrid: {store.enable_hybrid}")
        
        # 验证 path 字段是 None
        assert store.path is None, f"path 应该是 None，但实际是: {store.path}"
        print("✅ path 字段正确设置为 None")
        
        return True
        
    except Exception as e:
        print(f"❌ 应用补丁后仍然失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_patch_with_path_param():
    """测试传递 path 参数的情况"""
    print("\n=== 测试传递 path 参数的情况 ===")
    
    # 应用补丁
    from src.utils.patches import patch_qdrant_vector_store
    patch_qdrant_vector_store()
    
    from llama_index.vector_stores.qdrant import QdrantVectorStore
    mock_client = Mock()
    
    try:
        # 测试传递 path 参数（旧版本风格）
        store = QdrantVectorStore(
            collection_name="test_collection",
            client=mock_client,
            path="/some/path",  # 旧版本参数
            enable_hybrid=False
        )
        
        print("✅ 传递 path 参数时成功创建实例")
        print(f"   path 字段值: {store.path}")
        
        # 验证 path 被设置为 None（因为补丁移除了它）
        assert store.path is None, f"path 应该被设置为 None，但实际是: {store.path}"
        print("✅ path 参数被正确处理（设置为 None）")
        
        return True
        
    except Exception as e:
        print(f"❌ 传递 path 参数时失败: {e}")
        return False

if __name__ == "__main__":
    print("测试 QdrantVectorStore Pydantic 验证修复")
    print("=" * 50)
    
    # 运行测试
    test1_success = test_patch_solves_pydantic_validation()
    test2_success = test_patch_with_path_param()
    
    print("\n" + "=" * 50)
    print("测试结果:")
    print(f"  测试1（基本验证）: {'✅ 通过' if test1_success else '❌ 失败'}")
    print(f"  测试2（path参数）: {'✅ 通过' if test2_success else '❌ 失败'}")
    
    if test1_success and test2_success:
        print("\n🎉 所有测试通过！补丁成功修复了 QdrantVectorStore Pydantic 验证问题。")
        sys.exit(0)
    else:
        print("\n❌ 测试失败，需要进一步调试。")
        sys.exit(1)