package com.infoepoch.pms.agent.platform.agent.adapter.out.ai;

import com.alibaba.cloud.ai.graph.agent.interceptor.ToolCallHandler;
import com.alibaba.cloud.ai.graph.agent.interceptor.ToolCallRequest;
import com.alibaba.cloud.ai.graph.agent.interceptor.ToolCallResponse;
import com.alibaba.cloud.ai.graph.agent.interceptor.ToolInterceptor;
import com.infoepoch.pms.agent.platform.shared.observation.ToolExecutionTraceBuffer;
import com.infoepoch.pms.agent.platform.shared.observation.ToolExecutionTraceEvent;
import lombok.RequiredArgsConstructor;

/**
 * 工具执行轨迹拦截器。
 */
@RequiredArgsConstructor
public class ToolExecutionTraceInterceptor extends ToolInterceptor {

    private final ToolExecutionTraceBuffer traceBuffer;
    private final String requestKey;

    /**
     * 拦截工具调用并记录 running/finished/failed 三类轨迹事件。
     *
     * @param request 工具调用请求
     * @param handler 工具调用处理器
     * @return 工具调用响应
     */
    @Override
    public ToolCallResponse interceptToolCall(ToolCallRequest request, ToolCallHandler handler) {
        String toolDisplayName = request.getToolName();

        traceBuffer.append(requestKey, ToolExecutionTraceEvent.running(
                request.getToolCallId(), request.getToolName(), toolDisplayName,
                request.getArguments(), request.getToolName()));

        try {
            ToolCallResponse response = handler.call(request);
            traceBuffer.append(requestKey, ToolExecutionTraceEvent.finished(
                    request.getToolCallId(), request.getToolName(), toolDisplayName,
                    request.getArguments(), response.getResult(), request.getToolName()));
            return response;
        } catch (Exception ex) {
            traceBuffer.append(requestKey, ToolExecutionTraceEvent.failed(
                    request.getToolCallId(), request.getToolName(), toolDisplayName,
                    request.getArguments(), ex.getMessage(), request.getToolName()));
            throw ex;
        }
    }

    /**
     * 返回拦截器名称。
     *
     * @return 拦截器名称
     */
    @Override
    public String getName() {
        return "ToolExecutionTraceInterceptor";
    }
}
