#!/usr/bin/env python3
"""
feature_retriever_cli.py - 功能需求检索命令行工具（简化版）
专注于自然语言输入和多推理约束分析
"""
import sys
import json
import time
from pathlib import Path
from typing import Dict

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from feature_retriever import FeatureRetriever
from config import VECTOR_DB_PATH, METADATA_PATH, KNOWLEDGE_GRAPH_PATH
import logging
logger = logging.getLogger(__name__)

def display_result(result: Dict, query: str):
    """显示分析结果"""
    print("\n" + "=" * 80)
    print("功能需求实现分析报告")
    print("=" * 80)

    # 查询信息
    print(f"查询: {query}")
    print(f"分析时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")

    # 实现状态
    status_icon = "✅" if result.get("implemented") else "❌"
    status_text = "已实现" if result.get("implemented") else "未实现"
    print(f"\n实现状态: {status_icon} {status_text}")
    print(f"综合评分: {result.get('total_score', 0):.3f}")
    print(f"判断理由: {result.get('reason', '无理由')}")

    # 最相关函数
    if result.get("most_relevant_function"):
        rel_func = result["most_relevant_function"]
        print(f"\n最相关函数: {rel_func.get('name')}")
        print(f"所在文件: {rel_func.get('file')}")
        print(f"语义相似度: {rel_func.get('similarity', 0):.3f}")
        if rel_func.get("summary"):
            print(f"功能摘要: {rel_func.get('summary')}")

    # 约束分析详情
    print(f"\n约束分析详情 ({result.get('passed_constraints', 0)}/{result.get('total_constraints', 0)} 通过):")
    print("-" * 60)

    constraint_scores = result.get("constraint_scores", {})

    constraint_descriptions = {
        "semantic_constraint": "语义相似度约束",
        "call_chain_constraint": "调用链完整性约束",
        "modularity_constraint": "功能模块性约束",
        "architecture_constraint": "架构合理性约束"
    }

    for constraint_name, data in constraint_scores.items():
        constraint_desc = constraint_descriptions.get(constraint_name, constraint_name)
        passed_icon = "✅" if data.get("passed") else "❌"
        score = data.get("score", 0)
        weight = data.get("weight", 0)
        weighted = data.get("weighted_score", 0)

        print(f"{passed_icon} {constraint_desc}:")
        print(f"  评分: {score:.3f} | 权重: {weight:.2f} | 加权: {weighted:.3f}")

    # 相关函数统计
    print(f"\n相关函数统计:")
    print(f"  语义匹配函数数: {result.get('relevant_functions_count', 0)}")

    # 实现建议
    print(f"\n实现建议:")
    if result.get("implemented"):
        print("  ✅ 该功能在代码库中已有良好实现，建议：")
        print("    1. 参考最相关函数的实现逻辑")
        print("    2. 检查调用关系是否满足当前需求")
        print("    3. 如有扩展需求，可基于现有函数进行修改")
    else:
        print("  ❌ 该功能在代码库中未完全实现，建议：")
        print("    1. 检查约束分析详情，了解薄弱环节")
        print("    2. 可能需要新增函数或扩展现有函数")
        print("    3. 设计时参考相似功能模块的架构")

    print("=" * 80)


def save_result_to_file(result: Dict, query: str, output_file: str = "analysis_result.json"):
    """保存结果到文件"""
    result_data = {
        "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
        "query": query,
        "result": result
    }

    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(result_data, f, indent=2, ensure_ascii=False)
        print(f"\n分析结果已保存到: {output_file}")
    except Exception as e:
        print(f"保存结果失败: {e}")


def main():
    """命令行主函数"""
    print("卫星代码功能需求检索分析系统")
    print("=" * 60)
    print("功能: 基于多推理约束分析功能实现状态")
    print("约束包括:")
    print("  1. 语义相似度约束")
    print("  2. 调用链完整性约束")
    print("  3. 功能模块性约束")
    print("  4. 架构合理性约束")
    print("=" * 60)

    # 初始化检索器
    config = {
        "vector_db_path": VECTOR_DB_PATH,
        "metadata_path": METADATA_PATH,
        "knowledge_graph_path": KNOWLEDGE_GRAPH_PATH
    }

    try:
        retriever = FeatureRetriever(config)
        if not retriever.load_knowledge_base():
            print("加载知识库失败，请检查配置文件")
            sys.exit(1)

        print(f"知识库加载成功: {len(retriever.metadatas)} 个函数")
        print("输入自然语言描述功能需求进行分析")
        print("输入 'quit' 或 'exit' 退出")
        print("=" * 60)

        while True:
            try:
                query = input("\n请输入功能需求描述: ").strip()

                if query.lower() in ["quit", "exit", "q"]:
                    print("再见!")
                    break

                if not query:
                    print("请输入功能需求描述")
                    continue

                print(f"\n正在分析: {query}")
                print("正在执行多约束分析...")

                # 执行分析
                result = retriever.analyze_with_multiple_constraints(query)

                # 显示结果
                display_result(result, query)

                # 询问是否保存结果
                save_option = input("\n是否保存分析结果? (y/n): ").strip().lower()
                if save_option == 'y':
                    timestamp = time.strftime("%Y%m%d_%H%M%S")
                    output_file = f"analysis_{timestamp}.json"
                    save_result_to_file(result, query, output_file)

                # 询问是否继续
                continue_option = input("\n是否继续分析? (y/n): ").strip().lower()
                if continue_option != 'y':
                    print("再见!")
                    break

            except KeyboardInterrupt:
                print("\n\n分析被中断，输入 'quit' 退出")
            except Exception as e:
                print(f"分析过程中出错: {e}")
                logger.error(f"分析过程错误: {e}", exc_info=True)

    except Exception as e:
        print(f"初始化失败: {e}")
        logger.error(f"系统初始化错误: {e}", exc_info=True)
        sys.exit(1)


if __name__ == "__main__":
    main()