"""
重构代码测试脚本
验证组件化后的代码是否正常工作
"""
import sys
from pathlib import Path


def test_imports():
    """测试所有模块是否可以正常导入"""
    print("=" * 60)
    print("测试1: 模块导入测试")
    print("=" * 60)
    
    try:
        # 测试配置模块
        print("✓ 正在导入配置模块...")
        from src.config import Config
        print(f"  ✅ Config 导入成功")
        
        # 测试嵌入模块
        print("✓ 正在导入嵌入模块...")
        from src.embeddings import SiliconFlowEmbedding
        print(f"  ✅ SiliconFlowEmbedding 导入成功")
        
        # 测试分词器模块
        print("✓ 正在导入分词器模块...")
        from src.tokenizers import JiebaTokenizer, create_tokenizer
        print(f"  ✅ JiebaTokenizer 导入成功")
        
        # 测试工具模块
        print("✓ 正在导入工具模块...")
        from src.utils import setup_logger, patch_qdrant_vector_store
        print(f"  ✅ Utils 模块导入成功")
        
        # 测试存储模块
        print("✓ 正在导入存储模块...")
        from src.storage import VectorStoreManager, BM25StoreManager
        print(f"  ✅ Storage 模块导入成功")
        
        # 测试核心模块
        print("✓ 正在导入核心模块...")
        from src.core import RAGSystem
        print(f"  ✅ RAGSystem 导入成功")
        
        # 测试MCP处理器
        print("✓ 正在导入MCP处理器...")
        from src.mcp.handlers import MCPHandlers
        print(f"  ✅ MCPHandlers 导入成功")
        
        print("\n✅ 所有模块导入测试通过！\n")
        return True
        
    except ImportError as e:
        print(f"\n❌ 导入失败: {e}\n")
        import traceback
        traceback.print_exc()
        return False


def test_config():
    """测试配置模块"""
    print("=" * 60)
    print("测试2: 配置模块测试")
    print("=" * 60)
    
    try:
        from src.config import Config
        
        # 测试配置显示
        print("✓ 测试配置显示...")
        config_info = Config.display()
        print(f"  配置项数量: {len(config_info)}")
        print(f"  检索模式: {Config.RETRIEVAL_MODE}")
        print(f"  存储类型: {Config.VECTOR_STORE_TYPE}")
        
        # 测试目录确保
        print("✓ 测试目录创建...")
        Config.ensure_directories()
        print(f"  索引目录: {Config.INDEX_STORAGE_DIR.exists()}")
        print(f"  BM25目录: {Config.BM25_STORAGE_DIR.exists()}")
        
        print("\n✅ 配置模块测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ 配置测试失败: {e}\n")
        import traceback
        traceback.print_exc()
        return False


def test_tokenizer():
    """测试分词器"""
    print("=" * 60)
    print("测试3: 分词器测试")
    print("=" * 60)
    
    try:
        from src.tokenizers import create_tokenizer
        
        # 创建中文分词器
        print("✓ 创建中文分词器...")
        tokenizer = create_tokenizer(language="chinese")
        
        # 测试分词
        test_text = "RAG技术是一种检索增强生成的方法"
        tokens = tokenizer.tokenize(test_text)
        print(f"  原文: {test_text}")
        print(f"  分词结果: {' / '.join(tokens)}")
        print(f"  Token数量: {len(tokens)}")
        
        print("\n✅ 分词器测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ 分词器测试失败: {e}\n")
        import traceback
        traceback.print_exc()
        return False


def test_storage_managers():
    """测试存储管理器"""
    print("=" * 60)
    print("测试4: 存储管理器测试")
    print("=" * 60)
    
    try:
        from src.storage import VectorStoreManager, BM25StoreManager
        from src.config import Config
        
        # 测试向量存储管理器
        print("✓ 测试向量存储管理器...")
        vector_manager = VectorStoreManager(config=Config)
        print(f"  ✅ VectorStoreManager 创建成功")
        
        # 测试BM25存储管理器
        print("✓ 测试BM25存储管理器...")
        bm25_manager = BM25StoreManager(config=Config)
        print(f"  ✅ BM25StoreManager 创建成功")
        
        print("\n✅ 存储管理器测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ 存储管理器测试失败: {e}\n")
        import traceback
        traceback.print_exc()
        return False


def test_rag_system():
    """测试RAG系统"""
    print("=" * 60)
    print("测试5: RAG系统测试")
    print("=" * 60)
    
    try:
        from src.core import RAGSystem
        from src.config import Config
        
        print("✓ 创建RAG系统实例...")
        rag = RAGSystem(config=Config)
        print(f"  ✅ RAGSystem 创建成功")
        
        print("✓ 测试索引统计...")
        stats = rag.get_index_stats()
        print(f"  检索模式: {stats.get('retrieval_mode')}")
        print(f"  向量索引存在: {stats.get('vector_index_exists')}")
        print(f"  BM25启用: {stats.get('bm25_enabled')}")
        
        print("\n✅ RAG系统测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ RAG系统测试失败: {e}\n")
        import traceback
        traceback.print_exc()
        return False


def test_mcp_handlers():
    """测试MCP处理器"""
    print("=" * 60)
    print("测试6: MCP处理器测试")
    print("=" * 60)
    
    try:
        from src.mcp.handlers import MCPHandlers
        
        print("✓ 创建MCP处理器...")
        handlers = MCPHandlers()
        print(f"  ✅ MCPHandlers 创建成功")
        
        print("✓ 测试工具列表...")
        tools = handlers.tools.list_tools()
        print(f"  可用工具数量: {len(tools)}")
        for tool in tools:
            print(f"    - {tool.name}: {tool.description[:50]}...")
        
        print("✓ 测试资源列表...")
        resources = handlers.resources.list_resources()
        print(f"  可用资源数量: {len(resources)}")
        for resource in resources:
            print(f"    - {resource.name}: {resource.uri}")
        
        print("✓ 测试提示词列表...")
        prompts = handlers.prompts.list_prompts()
        print(f"  可用提示词数量: {len(prompts)}")
        for prompt in prompts:
            print(f"    - {prompt.name}: {prompt.description[:50]}...")
        
        print("\n✅ MCP处理器测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ MCP处理器测试失败: {e}\n")
        import traceback
        traceback.print_exc()
        return False




def main():
    """主测试函数"""
    print("\n")
    print("╔════════════════════════════════════════════════════════════╗")
    print("║            RAG系统组件化重构 - 测试验证               ║")
    print("╚════════════════════════════════════════════════════════════╝")
    print()
    
    # 运行所有测试
    tests = [
        ("模块导入", test_imports),
        ("配置模块", test_config),
        ("分词器", test_tokenizer),
        ("存储管理器", test_storage_managers),
        ("RAG系统", test_rag_system),
        ("MCP处理器", test_mcp_handlers),
    ]
    
    results = []
    for name, test_func in tests:
        result = test_func()
        results.append((name, result))
    
    # 打印总结
    print("=" * 60)
    print("测试总结")
    print("=" * 60)
    
    passed = sum(1 for _, r in results if r)
    total = len(results)
    
    for name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"{status} - {name}")
    
    print("=" * 60)
    print(f"总计: {passed}/{total} 测试通过")
    
    if passed == total:
        print("🎉 所有测试全部通过！组件化重构成功！")
        print("=" * 60)
        return 0
    else:
        print("⚠️  部分测试失败，请检查错误信息")
        print("=" * 60)
        return 1


if __name__ == "__main__":
    sys.exit(main())
