#!/usr/bin/env python3
"""
直接测试文档列表功能
"""
import sys
import os
import json
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from src.core.index_manager import IndexManager
from src.config import get_config_manager

def test_direct_document_list():
    """直接测试文档列表功能"""
    print("=" * 60)
    print("直接测试文档列表功能")
    print("=" * 60)
    
    # 获取配置
    config = get_config_manager()
    vector_storage_dir = config.paths.vector_storage_dir
    print(f"配置路径: {vector_storage_dir}")
    
    if vector_storage_dir is None:
        print("❌ 向量存储目录为None")
        return False
    
    # 创建IndexManager
    index_manager = IndexManager(config)
    
    # 尝试直接读取文档存储
    docstore_path = vector_storage_dir / "docstore.json"
    print(f"文档存储路径: {docstore_path}")
    
    if not docstore_path.exists():
        print("❌ 文档存储文件不存在")
        return False
    
    # 读取文档存储
    try:
        with open(docstore_path, 'r', encoding='utf-8') as f:
            docstore_data = json.load(f)
        
        print(f"✅ 成功读取文档存储文件")
        
        # 分析文档存储结构
        if "docstore/ref_doc_info" in docstore_data:
            ref_docs = docstore_data["docstore/ref_doc_info"]
            print(f"引用文档数量: {len(ref_docs)}")
            
            for i, (doc_id, doc_info) in enumerate(list(ref_docs.items())[:5]):
                print(f"  {i+1}. ID: {doc_id}")
                print(f"     元数据: {doc_info.get('metadata', {})}")
                print(f"     节点数: {len(doc_info.get('node_ids', []))}")
        
        if "docstore/data" in docstore_data:
            nodes = docstore_data["docstore/data"]
            print(f"节点数量: {len(nodes)}")
            
            for i, (node_id, node_data) in enumerate(list(nodes.items())[:3]):
                print(f"  {i+1}. 节点ID: {node_id}")
                if "__data__" in node_data:
                    text = node_data["__data__"].get("text", "")
                    preview = text[:100] + "..." if len(text) > 100 else text
                    print(f"     文本预览: {preview}")
        
        return True
        
    except Exception as e:
        print(f"❌ 读取文档存储失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_mcp_list_documents():
    """测试MCP文档列表功能"""
    print("\n" + "=" * 60)
    print("测试MCP文档列表功能")
    print("=" * 60)
    
    try:
        from src.services.rag_service import RAGService
        
        # 创建RAG服务
        config = get_config_manager()
        service = RAGService(config)
        
        # 测试list_documents方法
        print("调用service.list_documents()...")
        result = service.list_documents(limit=10)
        
        print(f"结果成功: {result.get('success')}")
        print(f"文档数量: {result.get('total_count', 0)}")
        
        if result.get('success'):
            documents = result.get('documents', [])
            print(f"文档列表: {len(documents)} 个文档")
            for i, doc in enumerate(documents[:5]):
                print(f"  {i+1}. ID: {doc.get('doc_id')}")
                print(f"     预览: {doc.get('text_preview')}")
                print(f"     长度: {doc.get('text_length')}")
        else:
            print(f"❌ 错误: {result.get('error')}")
        
        return result.get('success', False)
        
    except Exception as e:
        print(f"❌ 测试MCP功能失败: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    print("开始测试文档功能...")
    
    # 测试直接文档列表
    direct_success = test_direct_document_list()
    
    # 测试MCP文档列表
    mcp_success = test_mcp_list_documents()
    
    print("\n" + "=" * 60)
    print("测试结果:")
    print(f"直接文档列表: {'✅ 成功' if direct_success else '❌ 失败'}")
    print(f"MCP文档列表: {'✅ 成功' if mcp_success else '❌ 失败'}")
    print("=" * 60)