#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
setup.py - MCP工具函数包装模块
测试使用
定义MCP服务器所需的异步工具函数，这些函数调用src.function模块中的相应函数。
"""
import asyncio
import json
import os
import sys
import time
from typing import Any, Dict
from pathlib import Path



from src.function.upload import upload_for_one_directory
from src.function.seprate import separate_series_by_patient
from src.function.task_manager import run_task_in_background, get_task_status
import time
from src.utils.config_loader import get_default_config
# 测试代码已注释，避免在模块导入时执行

#拆分测试
# now=time.time()
# print(separate_series_by_patient(r"C:\Users\13167\Desktop\新建文件夹 (2)\测试4"))
# print(time.time()-now)
#上传测试
#print(upload_for_one_directory(r'C:\Users\13167\Desktop\新建文件夹 (2)\测试4\P10288241\1.3.12.2.1107.5.1.4.246797.30000025060909352104600091440\sub_phase_1',get_default_config(),'1'))


from src.setup import separate_series_by_patient_tool, get_separate_task_status_tool,Analysis_dicom_directory_tool

# def main():
#     loop = asyncio.get_event_loop()
# import asyncio

# async def main():
#     import time
#     now=time.time()
#     result=await Analysis_dicom_directory_tool(r"C:\Users\13167\Desktop\新建文件夹 (2)\测试4\P10288241\1.3.12.2.1107.5.1.4.246797.30000025060909352104600091440\sub_phase_1","1")
#     print(result)
#     print(time.time()-now)

  



# asyncio.run(main())

from src.setup import export_measurement_csv_tool,get_all_studies_and_series_tool

async def main():
            # export_measurement_csv_tool 需要接收 List[str]，不是单个字符串
            study_uids = ["1.2.86.76547135.7.202506100822145607.5096"]  # 传入列表格式
            result = await export_measurement_csv_tool(study_uids)
            print(result)
            result2=await get_all_studies_and_series_tool("P10288241")
            print(result2)




asyncio.run(main())





# async def Analysis_dicom_directory_tool(directory_path: str, series_type: str) -> Dict[str, Any]:
#     """
#     分析DICOM目录并上传到远端分析服务的异步工具函数
#
#     Args:
#         directory_path: 包含待分析DICOM序列的本地目录路径
#         series_type: 分析流程类型，'1'=主动脉分析，'9'=二尖瓣分析
#
#     Returns:
#         包含上传结果的字典，格式符合MCP工具输出格式
#     """
#     try:
#         config = get_default_config()
#         # 调用src.function.upload模块中的函数
#         result = upload_for_one_directory(directory_path, config, series_type)
#         return result
#     except Exception as e:
#         import traceback
#         error_info = f"处理过程中发生错误: {str(e)}\n详细信息:\n{traceback.format_exc()}"
#         return {
#             "content": [
#                 {
#                     "type": "text",
#                     "text": json.dumps({"error": True, "message": error_info}, ensure_ascii=False)
#                 }
#             ]
#         }
#
#
# async def separate_series_by_patient_tool(directory_path: str, async_mode: bool = True) -> Dict[str, Any]:
#     """
#     按患者和序列拆分目录下的DICOM文件的异步工具函数
#
#     如果async_mode=True，则在后台执行并立即返回任务ID；否则同步执行（可能超时）
#
#     Args:
#         directory_path: 待整理的顶层目录路径
#         async_mode: 是否异步执行，默认为True
#
#     Returns:
#         包含拆分结果或任务ID的字典，格式符合MCP工具输出格式
#     """
#     try:
#         # 标准化路径格式
#         directory_path = fr'{directory_path}'
#
#         if async_mode:
#             # 后台执行模式：立即返回任务ID
#             # 任务状态文件将保存在 directory_path 目录中
#             task_id = run_task_in_background(separate_series_by_patient, directory_path, directory_path)
#             return {
#                 "content": [
#                     {
#                         "type": "text",
#                         "text": json.dumps({
#                             "task_id": task_id,
#                             "status": "running",
#                             "message": "任务已在后台启动，请使用 get_separate_task_status 工具查询进度",
#                             "directory_path": directory_path,
#                             "task_status_file": str(Path(directory_path) / f"task_{task_id}.json"),
#                             "async_mode": True
#                         }, ensure_ascii=False)
#                     }
#                 ]
#             }
#         else:
#             # 同步执行模式（不推荐，可能超时）
#             result = separate_series_by_patient(directory_path)
#             return result
#     except Exception as e:
#         import traceback
#         error_info = f"处理过程中发生错误: {str(e)}\n详细信息:\n{traceback.format_exc()}"
#         return {
#             "content": [
#                 {
#                     "type": "text",
#                     "text": json.dumps({"error": True, "message": error_info}, ensure_ascii=False)
#                 }
#             ]
#         }
#
#
# async def get_separate_task_status_tool(task_id: str, directory_path: str) -> Dict[str, Any]:
#     """
#     查询separate_series_by_patient任务状态的工具函数
#
#     当任务完成时，返回separate_series_by_patient的JSON内容，包括每个series的uid和文件路径
#
#     Args:
#         task_id: 任务ID
#         directory_path: 任务目录路径（fileforsep参数指定的目录）
#
#     Returns:
#         包含任务状态的字典，任务完成时返回separate_series_by_patient的JSON内容
#     """
#     try:
#         # 标准化路径格式
#         directory_path = fr'{directory_path}'
#         status = get_task_status(task_id, directory_path)
#         if status is None:
#             return {
#                 "content": [
#                     {
#                         "type": "text",
#                         "text": json.dumps({
#                             "error": True,
#                             "message": f"任务 {task_id} 不存在于目录 {directory_path}",
#                             "task_status_file": str(Path(directory_path) / f"task_{task_id}.json")
#                         }, ensure_ascii=False)
#                     }
#                 ]
#             }
#
#         # 如果任务完成，返回separate_series_by_patient的JSON内容
#         if status.get("status") == "completed" and status.get("result"):
#             result = status.get("result")
#             # result 是 separate_series_by_patient 返回的格式：
#             # {"content": [{"type": "text", "text": "..."}]}
#             # 我们需要提取其中的 JSON 内容
#             if isinstance(result, dict) and "content" in result:
#                 content_list = result.get("content", [])
#                 for content_item in content_list:
#                     if content_item.get("type") == "text":
#                         # 直接返回 separate_series_by_patient 的 JSON 内容
#                         return {
#                             "content": [
#                                 {
#                                     "type": "text",
#                                     "text": content_item.get("text", "")
#                                 }
#                             ]
#                         }
#             # 如果格式不符合预期，返回原始结果
#             return {
#                 "content": [
#                     {
#                         "type": "text",
#                         "text": json.dumps(result, ensure_ascii=False, indent=2)
#                     }
#                 ]
#             }
#
#         # 任务未完成或失败，返回任务状态
#         return {
#             "content": [
#                 {
#                     "type": "text",
#                     "text": json.dumps(status, ensure_ascii=False, indent=2)
#                 }
#             ]
#         }
#     except Exception as e:
#         import traceback
#         error_info = f"查询任务状态时发生错误: {str(e)}\n详细信息:\n{traceback.format_exc()}"
#         return {
#             "content": [
#                 {
#                     "type": "text",
#                     "text": json.dumps({"error": True, "message": error_info}, ensure_ascii=False)
#                 }
#             ]
#         }
# #
# #查询工具
# # async def get_result_tool(study_uid: str) -> Dict[str, Any]:
# #     """
# #     根据study_uid查询分析结果的异步工具函数
# #
# #     Args:
# #         study_uid: DICOM序列的StudyInstanceUID，用于查询分析结果
# #
# #     Returns:
# #         包含查询结果的字典，格式符合MCP工具输出格式
# #     """
# #     try:
# #         # 调用同步版本的get_result函数
# #         result = get_result_sync(study_uid)
# #         return result
# #     except Exception as e:
# #         import traceback
# #         error_info = f"查询结果时发生错误: {str(e)}\n详细信息:\n{traceback.format_exc()}"
# #         return {
# #             "content": [
# #                 {
# #                     "type": "text",
# #                     "text": json.dumps({"error": True, "message": error_info}, ensure_ascii=False)
# #                 }
# #             ]
# #         }
