"""
RAG 系统功能测试脚本
测试 CLI 功能和 MCP 功能是否可用
"""
import sys
import os
from pathlib import Path

def test_imports():
    """测试模块导入"""
    print("=" * 60)
    print("1️⃣  测试模块导入")
    print("=" * 60)
    
    try:
        # 测试核心模块
        print("\n📦 测试核心模块导入...")
        from src.core import RAGSystem
        print("  ✅ RAGSystem 导入成功")
        
        from src.config import Config
        print("  ✅ Config 导入成功")
        
        from src.embeddings import SiliconFlowEmbedding
        print("  ✅ SiliconFlowEmbedding 导入成功")
        
        from src.storage import VectorStoreManager, BM25StoreManager
        print("  ✅ VectorStoreManager 导入成功")
        print("  ✅ BM25StoreManager 导入成功")
        
        # 测试 MCP 模块
        print("\n📦 测试 MCP 模块导入...")
        from src.mcp.handlers import MCPToolsHandler
        print("  ✅ MCPToolsHandler 导入成功")
        
        from mcp.types import Tool, TextContent
        print("  ✅ MCP 类型导入成功")
        
        print("\n✅ 所有模块导入测试通过！\n")
        return True
        
    except ImportError as e:
        print(f"\n❌ 模块导入失败: {e}\n")
        return False


def test_config():
    """测试配置"""
    print("=" * 60)
    print("2️⃣  测试系统配置")
    print("=" * 60)
    
    try:
        from src.config import Config
        
        print("\n📋 系统配置:")
        print(f"  LLM 模型: {Config.LLM_MODEL}")
        print(f"  Embedding 模型: {Config.EMBEDDING_MODEL}")
        print(f"  检索模式: {Config.RETRIEVAL_MODE}")
        print(f"  使用 BM25: {Config.USE_BM25}")
        print(f"  使用 Qdrant: {Config.USE_QDRANT}")
        
        if Config.USE_QDRANT:
            print(f"  Qdrant URL: {Config.QDRANT_URL[:50]}...")
            print(f"  Qdrant 集合: {Config.QDRANT_COLLECTION_NAME}")
        
        print(f"  文档分块大小: {Config.CHUNK_SIZE}")
        print(f"  分块重叠: {Config.CHUNK_OVERLAP}")
        print(f"  Top K: {Config.SIMILARITY_TOP_K}")
        
        # 检查必需的 API keys
        print("\n🔑 API 密钥检查:")
        if Config.DEEPSEEK_API_KEY and Config.DEEPSEEK_API_KEY != "your_api_key_here":
            print(f"  ✅ DeepSeek API Key: {Config.DEEPSEEK_API_KEY[:20]}...")
        else:
            print("  ❌ DeepSeek API Key 未配置")
            
        if Config.SILICONFLOW_API_KEY and Config.SILICONFLOW_API_KEY != "your_api_key_here":
            print(f"  ✅ SiliconFlow API Key: {Config.SILICONFLOW_API_KEY[:20]}...")
        else:
            print("  ❌ SiliconFlow API Key 未配置")
        
        print("\n✅ 配置测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ 配置测试失败: {e}\n")
        return False


def test_rag_system():
    """测试 RAG 系统初始化"""
    print("=" * 60)
    print("3️⃣  测试 RAG 系统初始化")
    print("=" * 60)
    
    try:
        from src.core import RAGSystem
        from src.config import Config
        
        print("\n🚀 初始化 RAG 系统...")
        rag = RAGSystem(config=Config)
        
        print("  ✅ RAG 系统初始化成功")
        
        # 获取索引状态
        print("\n📊 获取索引状态...")
        stats = rag.get_index_stats()
        
        print(f"\n索引状态信息:")
        print(f"  检索模式: {stats.get('retrieval_mode', 'N/A')}")
        print(f"  向量索引存在: {stats.get('vector_index_exists', False)}")
        print(f"  BM25 已启用: {stats.get('bm25_enabled', False)}")
        
        if stats.get('bm25_enabled'):
            print(f"  BM25 索引存在: {stats.get('bm25_index_exists', False)}")
        
        print("\n✅ RAG 系统测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ RAG 系统测试失败: {e}")
        import traceback
        traceback.print_exc()
        print()
        return False


def test_mcp_handlers():
    """测试 MCP 处理器"""
    print("=" * 60)
    print("4️⃣  测试 MCP 处理器")
    print("=" * 60)
    
    try:
        from src.mcp.handlers import MCPToolsHandler
        
        print("\n🔧 初始化 MCP 工具处理器...")
        handler = MCPToolsHandler()
        
        print("  ✅ MCPToolsHandler 初始化成功")
        
        # 列出工具
        print("\n📋 列出可用的 MCP 工具:")
        tools = handler.list_tools()
        
        for i, tool in enumerate(tools, 1):
            print(f"\n  {i}. {tool.name}")
            print(f"     描述: {tool.description}")
            
            # 显示必需参数
            required = tool.inputSchema.get("required", [])
            if required:
                print(f"     必需参数: {', '.join(required)}")
        
        print(f"\n✅ 找到 {len(tools)} 个 MCP 工具")
        
        # 测试获取索引状态工具
        print("\n🔍 测试 get_index_status 工具调用...")
        result = handler.call_tool("get_index_status", {})
        
        if result and len(result) > 0:
            print("  ✅ get_index_status 工具调用成功")
        else:
            print("  ⚠️  get_index_status 返回空结果")
        
        print("\n✅ MCP 处理器测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ MCP 处理器测试失败: {e}")
        import traceback
        traceback.print_exc()
        print()
        return False


def test_cli_availability():
    """测试 CLI 可用性"""
    print("=" * 60)
    print("5️⃣  测试 CLI 可用性")
    print("=" * 60)
    
    try:
        cli_path = Path("cli.py")
        
        if not cli_path.exists():
            print("\n❌ cli.py 文件不存在\n")
            return False
        
        print(f"\n📄 CLI 文件: {cli_path}")
        print(f"  文件大小: {cli_path.stat().st_size} 字节")
        
        # 检查cli.py的可执行性
        print("\n📋 CLI 命令说明:")
        print("  可用命令:")
        print("    - python cli.py index --dir <目录>  # 构建索引")
        print("    - python cli.py query -q <问题>     # 查询")
        print("    - python cli.py status              # 查看状态")
        print("    - python cli.py config              # 查看配置")
        print("    - python cli.py delete              # 删除索引")
        
        print("\n✅ CLI 可用性测试通过！\n")
        return True
        
    except Exception as e:
        print(f"\n❌ CLI 可用性测试失败: {e}\n")
        return False


def main():
    """主测试函数"""
    print("\n")
    print("╔" + "=" * 58 + "╗")
    print("║" + " " * 10 + "RAG 系统功能测试" + " " * 32 + "║")
    print("╚" + "=" * 58 + "╝")
    print()
    
    results = []
    
    # 运行所有测试
    results.append(("模块导入", test_imports()))
    results.append(("系统配置", test_config()))
    results.append(("RAG 系统", test_rag_system()))
    results.append(("MCP 处理器", test_mcp_handlers()))
    results.append(("CLI 可用性", test_cli_availability()))
    
    # 汇总结果
    print("=" * 60)
    print("📊 测试结果汇总")
    print("=" * 60)
    
    passed = 0
    failed = 0
    
    for name, result in results:
        if result:
            print(f"  ✅ {name:<15} - 通过")
            passed += 1
        else:
            print(f"  ❌ {name:<15} - 失败")
            failed += 1
    
    print("=" * 60)
    print(f"\n总计: {passed + failed} 项测试")
    print(f"  ✅ 通过: {passed}")
    print(f"  ❌ 失败: {failed}")
    
    if failed == 0:
        print("\n🎉 所有测试通过！系统功能正常！\n")
        return 0
    else:
        print(f"\n⚠️  有 {failed} 项测试失败，请检查上述错误信息\n")
        return 1


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