package com.agent.management.engine.executor;

import com.agent.management.engine.NodeExecutionResult;
import com.agent.management.engine.NodeExecutor;
import com.agent.management.engine.NodeOutputEnvelope;
import com.agent.management.engine.NodeWorkspace;
import com.agent.management.engine.WorkflowContext;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户输入节点执行器
 * 从 context 中提取用户输入值，以变量名作为 key 写回上下文
 */
@Slf4j
@Component
public class UserInputExecutor implements NodeExecutor {

    @Override
    public String getType() {
        return "userInput";
    }

    @Override
    public NodeExecutionResult execute(String nodeId, JsonNode data, WorkflowContext context, NodeWorkspace workspace) {
        // 用户输入在运行时已通过 request.inputs 提供
        // 此节点的作用是：根据 variables 定义，将用户输入值规范化并注册到上下文
        JsonNode variablesNode = data.path("variables");
        Map<String, Object> output = new HashMap<>();

        if (variablesNode.isArray()) {
            for (JsonNode var : variablesNode) {
                String name = var.path("name").asText("");
                if (!name.isEmpty()) {
                    Object value = workspace.getVariable(name);
                    if (value != null) {
                        output.put(name, value);
                        log.debug("[UserInput] 变量 {} = {}", name, value);
                    } else {
                        log.warn("[UserInput] 变量 {} 未提供值", name);
                    }
                }
            }
        }

        return NodeExecutionResult.success(nodeId,
                NodeOutputEnvelope.success("用户输入已收集", output).toMap());
    }
}
