import json

# 工具名 → 实际函数的映射
TOOL_MAP = {
    "get_user_stats": get_user_stats,
    "lookup_vdot": lookup_vdot,
    "rag_search": rag_search,
}

def run_agent(user_query: str, user_id: str) -> str:
    messages = [
        {
            "role": "system",
            "content": "你是专业跑步教练 AI。可以查用户数据、查 VDOT 表、查知识库。"
                       f"当前用户 ID：{user_id}"
        },
        {
            "role": "user",
            "content": user_query
        },
    ]

    # 循环直到 AI 给出最终答案
    while True:
        response = ai.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            tools=tools,  # 把工具列表传给 AI
            tool_choice="auto"  # AI 自动决定要不要调工具
        )

        msg = response.choices[0].message

        # AI 不调工具了，直接给出最终回答
        if msg.tool_calls is None:
            return msg.content

        # AI 要调工具：逐个执行
        messages.append(msg)  # 把 AI 的意图加入历史
        for tc in msg.tool_calls:
            fn_name = tc.function.name
            fn_args = json.loads(tc.function.arguments)

            print(f"🔧 调用 {fn_name}({fn_args})")
            result = TOOL_MAP[fn_name](** fn_args)  # 真正执行函数
            print(f"📊 结果：{result}")

            # 把工具结果还给 AI
            messages.append({
                "role": "tool",
                "tool_call_id": tc.id,
                "content": json.dumps(result, ensure_ascii=False)
            })