"""
CLI 显示格式化模块
提供命令行界面的输出格式化功能
"""


def print_banner():
    """打印欢迎横幅"""
    banner = """
╔════════════════════════════════════════════════════════════╗
║                  RAG 知识库系统 CLI                        ║
║              基于 LlamaIndex 框架构建                      ║
╚════════════════════════════════════════════════════════════╝
    """
    print(banner)


def display_retrieve_result(result: dict):
    """
    显示检索结果
    
    Args:
        result: 检索结果字典
    """
    if not result["success"]:
        print("="*60)
        print(f"❌ 检索失败: {result['error']}")
        print("="*60)
        return
    
    # 显示检索结果
    print("="*60)
    print("📚 检索结果:")
    if result.get("query"):
        print(f"   查询: {result['query']}")
    if result.get("mode"):
        print(f"   检索模式: {result['mode']}")
    print(f"   找到 {result.get('count', 0)} 个相关文档片段")
    print("="*60)
    
    for doc in result["results"]:
        rank = doc.get('rank', 0)
        print(f"\n[排名 {rank}]")
        
        # 显示文件信息
        if doc.get('file_name'):
            print(f"📄 文件名: {doc['file_name']}")
        if doc.get('file_path'):
            print(f"📂 路径: {doc['file_path']}")
        
        # 显示分数
        if doc.get('score') is not None:
            mode = result.get('mode', '').lower()
            if mode == 'bm25':
                print(f"📊 BM25分数: {doc['score']:.4f} (词频统计分数)")
            elif mode == 'vector':
                print(f"📊 相似度: {doc['score']:.4f} (余弦相似度)")
            else:
                print(f"📊 融合分数: {doc['score']:.4f} (混合检索)")
        
        # 显示文档内容
        text = doc['text']
        print(f"📝 内容: {text[:500]}{'...' if len(text) > 500 else ''}")
        
        print("-" * 60)


def display_query_result(result: dict, show_sources: bool = False):
    """
    显示查询结果
    
    Args:
        result: 查询结果字典
        show_sources: 是否显示源文档
    """
    if not result["success"]:
        print("="*60)
        print(f"❌ 查询失败: {result['error']}")
        print("="*60)
        return
    
    # 显示答案
    print("="*60)
    print("📝 回答:")
    if result.get("mode"):
        print(f"   (检索模式: {result['mode']})")
    print("="*60)
    print(result["answer"])
    print("="*60)
    
    # 显示源文档（如果需要）
    if show_sources and result["sources"]:
        print("\n📚 相关文档片段:")
        print("-"*60)
        for i, source in enumerate(result["sources"], 1):
            print(f"\n[片段 {i}] (相似度: {source['score']:.4f})")
            print(f"内容: {source['text']}")
            if source.get('metadata'):
                print(f"元数据: {source['metadata']}")
        print("-"*60)
