import json
from datetime import time
from typing import Dict, Any

from src.api import find_result

from ..utils.config_loader import get_default_config


def get_result_sync(study_uid: str) -> Dict[str, Any]:
    """
    同步版本的get_result函数，根据study_uid查询分析结果

    Args:
        study_uid: DICOM序列的StudyInstanceUID

    Returns:
        包含查询结果的字典，格式符合MCP工具输出格式
    """
    try:
        config = get_default_config()
        cookie = "ls=" + config["cookie"]
        api_url = config["base_url"] + '/api/v2/getSeriesByStudyInstanceUID'

        def query_result(study_uid):
            """内部查询函数"""
            study_uid, series_uid, s_type, status = find_result(
                api_url, study_uid, cookie
            )
            return status, study_uid, series_uid, s_type

        # 查询结果，最多等待120秒
        result_found = False
        final_status = None
        final_study_uid = None
        final_series_uid = None
        final_s_type = None

        for i in range(120):
            status, study_uid, series_uid, s_type = query_result(study_uid)
            if status is not None:
                if int(status) == 42:
                    result_found = True
                    final_status = status
                    final_study_uid = study_uid
                    final_series_uid = series_uid
                    final_s_type = s_type
                    break
                elif int(status) == 41:
                    # 分析中，继续等待
                    time.sleep(1)
                elif int(status) == 44:
                    # 分析失败
                    break
                time.sleep(1)
            else:
                break

        result_dict = {}
        if result_found:
            result_dict["url"] = (
                f"{config['base_url']}/viewer/{final_study_uid}"
                f"?seriesInstanceUID={final_series_uid}"
                f"&type={final_s_type}&status=42"
            )
        else:
            result_dict["message"] = (
                f"查询超时，请确定是否进行上传，"
                f"或系统中查看结果: {config['base_url']}/study/studylist"
            )

        return {
            "content": [
                {
                    "type": "text",
                    "text": json.dumps(result_dict, 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)
                }
            ]
        }
