#!/usr/bin/env python3
"""
最终测试补丁是否修复了 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_patch():
    """测试补丁是否修复了问题"""
    print("=== 测试 QdrantVectorStore 补丁修复 ===")
    
    # 1. 首先测试未应用补丁的情况（应该会失败）
    print("\n1. 测试未应用补丁的情况...")
    try:
        from llama_index.vector_stores.qdrant import QdrantVectorStore as OriginalQdrantVectorStore
        
        # 创建一个模拟的 QdrantClient，避免实际连接
        with patch('qdrant_client.QdrantClient'):
            with patch('qdrant_client.AsyncQdrantClient'):
                # 尝试创建实例
                store = OriginalQdrantVectorStore(
                    collection_name="test_collection",
                    client=Mock(),
                    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"✅ 未应用补丁时按预期失败（Pydantic 验证错误）")
            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
        
        # 创建一个模拟的 QdrantClient
        mock_client = Mock()
        # 模拟 get_collection 方法，避免连接错误
        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 = PatchedQdrantVectorStore(
                    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}")
                    if store.path is None:
                        print("✅ path 字段正确设置为 None")
                    else:
                        print(f"⚠️  path 字段不是 None: {store.path}")
                
                return True
                
    except Exception as e:
        print(f"❌ 应用补丁后仍然失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_with_real_config():
    """使用真实配置测试"""
    print("\n=== 使用真实配置测试 ===")
    
    # 应用补丁
    from src.utils.patches import patch_qdrant_vector_store
    patch_qdrant_vector_store()
    
    # 导入必要的模块
    from src.config.settings import get_settings
    from src.storage.strategies.qdrant_strategy import QdrantStorageStrategy
    from src.types import StorageConfig, StorageBackend
    
    try:
        # 获取配置
        settings = get_settings()
        print(f"配置信息:")
        print(f"  QDRANT_HOST: {settings.QDRANT_HOST}")
        print(f"  QDRANT_PORT: {settings.QDRANT_PORT}")
        print(f"  QDRANT_COLLECTION_NAME: {settings.QDRANT_COLLECTION_NAME}")
        
        # 创建存储配置
        config = StorageConfig(
            backend=StorageBackend.QDRANT,
            qdrant_host=settings.QDRANT_HOST,
            qdrant_port=settings.QDRANT_PORT,
            qdrant_collection_name=settings.QDRANT_COLLECTION_NAME,
        )
        
        # 创建 Qdrant 存储策略
        strategy = QdrantStorageStrategy(config)
        
        # 尝试初始化
        print("\n尝试初始化 Qdrant 存储策略...")
        result = strategy.initialize()
        
        if result.success:
            print(f"✅ Qdrant 存储策略初始化成功: {result.message}")
            return True
        else:
            print(f"❌ Qdrant 存储策略初始化失败: {result.error}")
            return False
            
    except Exception as e:
        print(f"❌ 配置测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    print("最终测试 QdrantVectorStore Pydantic 验证修复")
    print("=" * 60)
    
    # 运行测试
    test1_success = test_patch()
    
    # 尝试真实配置测试（可能会因为 Qdrant 服务器不可用而失败）
    test2_success = False
    try:
        test2_success = test_with_real_config()
    except Exception as e:
        print(f"真实配置测试跳过（可能缺少依赖）: {e}")
    
    print("\n" + "=" * 60)
    print("测试结果总结:")
    print(f"  测试1（补丁验证）: {'✅ 通过' if test1_success else '❌ 失败'}")
    print(f"  测试2（真实配置）: {'✅ 通过' if test2_success else '⚠️  跳过/失败'}")
    
    if test1_success:
        print("\n🎉 补丁验证通过！QdrantVectorStore Pydantic 验证问题已修复。")
        print("\n现在可以运行索引构建命令来验证完整功能:")
        print("  python cli.py index --dir ./data")
        sys.exit(0)
    else:
        print("\n❌ 补丁验证失败，需要进一步调试。")
        sys.exit(1)