package tech.easyflow.agent.runtime.tool;

import com.easyagents.flow.core.chain.runtime.ChainExecutor;
import com.easyagents.core.model.chat.tool.Tool;
import org.springframework.stereotype.Service;
import tech.easyflow.ai.easyagents.tool.WorkflowTool;
import tech.easyflow.ai.easyagentsflow.support.PublishedWorkflowDefinitionIds;
import tech.easyflow.ai.entity.Workflow;

import java.util.Map;

/**
 * Agent Workflow 工具执行器。
 */
@Service
public class WorkflowToolExecutor {

    private final ChainExecutor chainExecutor;

    /**
     * 创建 Workflow 工具执行器。
     *
     * @param chainExecutor 工作流执行器
     */
    public WorkflowToolExecutor(ChainExecutor chainExecutor) {
        this.chainExecutor = chainExecutor;
    }

    /**
     * 构建 Workflow 工具声明来源。
     *
     * @param workflow 工作流
     * @return 工具声明来源
     */
    public Tool buildTool(Workflow workflow) {
        return new WorkflowTool(workflow, true, definitionId(workflow));
    }

    /**
     * 执行 Workflow 工具。
     *
     * @param workflow 工作流
     * @param arguments 执行参数
     * @return 执行结果
     */
    public AgentToolExecutionResult execute(Workflow workflow, Map<String, Object> arguments) {
        Object result = chainExecutor.execute(definitionId(workflow), arguments == null ? Map.of() : arguments);
        return new AgentToolExecutionResult(result, resolveBusinessExecutionId(result));
    }

    private String definitionId(Workflow workflow) {
        return PublishedWorkflowDefinitionIds.published(String.valueOf(workflow == null ? null : workflow.getId()));
    }

    private String resolveBusinessExecutionId(Object result) {
        if (result instanceof Map<?, ?> map) {
            Object value = firstValue(map, "executionId", "executeId", "chainId", "runId");
            return value == null ? null : String.valueOf(value);
        }
        return null;
    }

    private Object firstValue(Map<?, ?> map, String... keys) {
        for (String key : keys) {
            if (map.containsKey(key)) {
                return map.get(key);
            }
        }
        return null;
    }
}
