package com.flowable.devops.workflow.node;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.flowable.devops.entity.NodeType;
import com.flowable.devops.workflow.model.NodeExecutionContext;
import com.flowable.devops.workflow.model.NodeExecutionResult;
import com.flowable.devops.workflow.model.NodeInput;
import com.flowable.devops.workflow.plugin.NodePlugin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 文本处理节点
 * 
 * 功能：
 * - 转大写
 * - 转小写
 * - 反转字符串
 * - 去除空格
 * 
 * 这是一个完整的插件示例，展示如何使用@NodePlugin注解
 * 
 * @author Flowable Team
 * @since 1.0.0
 */
@Slf4j
@NodePlugin(
    id = "text_processor",
    name = "textProcessor",
    displayName = "Text Processor",
    category = NodeType.NodeCategory.TRANSFORM,
    version = "1.0.0",
    author = "Flowable Team",
    description = "文本处理工具，支持大小写转换、字符串反转和去除空格",
    icon = "font-size",
    enabled = true,
    homepage = "https://github.com/flowable-devops/plugins/text-processor",
    license = "Apache-2.0"
)
@Component
public class TextProcessorNode implements WorkflowNode {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public NodeType getMetadata() {
        NodeType nodeType = new NodeType();
        nodeType.setId("text_processor");
        nodeType.setName("textProcessor");
        nodeType.setDisplayName("Text Processor");
        nodeType.setCategory(NodeType.NodeCategory.TRANSFORM);
        nodeType.setIcon("font-size");
        nodeType.setDescription("文本处理工具，支持多种文本转换操作");
        nodeType.setImplementationClass(this.getClass().getName());
        nodeType.setEnabled(true);
        
        // 字段定义
        nodeType.setFields(createFieldsJson());
        
        // 输出结构
        nodeType.setOutputSchema(createOutputSchemaJson());
        
        return nodeType;
    }
    
    /**
     * 创建字段定义JSON
     */
    private JsonNode createFieldsJson() {
        ArrayNode fields = objectMapper.createArrayNode();
        
        // 输入文本字段
        ObjectNode inputField = objectMapper.createObjectNode();
        inputField.put("name", "text");
        inputField.put("label", "Input Text");
        inputField.put("type", "textarea");
        inputField.put("required", true);
        inputField.put("supportsExpression", true);
        inputField.put("supportsFieldMapping", true);
        inputField.put("placeholder", "Enter text to process...");
        inputField.put("description", "要处理的文本内容");
        fields.add(inputField);
        
        // 操作类型字段
        ObjectNode operationField = objectMapper.createObjectNode();
        operationField.put("name", "operation");
        operationField.put("label", "Operation");
        operationField.put("type", "select");
        operationField.put("required", true);
        operationField.put("defaultValue", "uppercase");
        operationField.put("description", "选择要执行的操作");
        
        ArrayNode operations = objectMapper.createArrayNode();
        operations.add("uppercase");
        operations.add("lowercase");
        operations.add("reverse");
        operations.add("trim");
        operationField.set("options", operations);
        fields.add(operationField);
        
        return fields;
    }
    
    /**
     * 创建输出结构JSON Schema
     */
    private JsonNode createOutputSchemaJson() {
        ObjectNode schema = objectMapper.createObjectNode();
        schema.put("type", "object");
        
        ObjectNode properties = objectMapper.createObjectNode();
        
        // 处理结果
        ObjectNode result = objectMapper.createObjectNode();
        result.put("type", "string");
        result.put("description", "处理后的文本");
        properties.set("result", result);
        
        // 执行的操作
        ObjectNode operation = objectMapper.createObjectNode();
        operation.put("type", "string");
        operation.put("description", "执行的操作类型");
        properties.set("operation", operation);
        
        // 原始文本长度
        ObjectNode originalLength = objectMapper.createObjectNode();
        originalLength.put("type", "number");
        originalLength.put("description", "原始文本长度");
        properties.set("originalLength", originalLength);
        
        // 处理后文本长度
        ObjectNode resultLength = objectMapper.createObjectNode();
        resultLength.put("type", "number");
        resultLength.put("description", "处理后文本长度");
        properties.set("resultLength", resultLength);
        
        schema.set("properties", properties);
        return schema;
    }
    
    @Override
    public NodeExecutionResult execute(NodeInput input, NodeExecutionContext context) {
        LocalDateTime startTime = LocalDateTime.now();
        
        try {
            // 1. 获取输入参数（表达式已被解析）
            String text = input.getStringRequired("text");
            String operation = input.getString("operation", "uppercase");
            
            log.info("执行文本处理: operation={}, textLength={}", operation, text.length());
            log.debug("输入文本: {}", text);
            
            // 2. 验证输入
            validate(input);
            
            // 3. 执行操作
            String result = processText(text, operation);
            
            // 4. 构建输出
            Map<String, Object> output = new HashMap<>();
            output.put("result", result);
            output.put("operation", operation);
            output.put("originalLength", text.length());
            output.put("resultLength", result.length());
            
            LocalDateTime endTime = LocalDateTime.now();
            log.info("文本处理完成: {} 字符 -> {} 字符", text.length(), result.length());
            log.debug("输出文本: {}", result);
            
            return NodeExecutionResult.success(output, startTime, endTime);
            
        } catch (Exception e) {
            LocalDateTime endTime = LocalDateTime.now();
            log.error("文本处理失败: {}", e.getMessage(), e);
            return NodeExecutionResult.failed(
                e.getMessage(), 
                e.getClass().getSimpleName(), 
                startTime, 
                endTime
            );
        }
    }
    
    /**
     * 执行文本处理
     */
    private String processText(String text, String operation) {
        switch (operation) {
            case "uppercase":
                return text.toUpperCase();
                
            case "lowercase":
                return text.toLowerCase();
                
            case "reverse":
                return new StringBuilder(text).reverse().toString();
                
            case "trim":
                return text.trim();
                
            default:
                throw new IllegalArgumentException("Unknown operation: " + operation);
        }
    }
    
    @Override
    public void validate(NodeInput input) {
        // 验证必需参数
        String text = input.getStringRequired("text");
        
        // 验证文本不为空
        if (text.isEmpty()) {
            throw new IllegalArgumentException("Input text cannot be empty");
        }
        
        // 验证文本长度限制（避免处理超大文本）
        if (text.length() > 1000000) {  // 1MB
            throw new IllegalArgumentException("Input text too large (max 1MB)");
        }
        
        // 验证操作类型
        String operation = input.getString("operation");
        if (operation != null && 
            !operation.equals("uppercase") && 
            !operation.equals("lowercase") && 
            !operation.equals("reverse") && 
            !operation.equals("trim")) {
            throw new IllegalArgumentException(
                "Invalid operation: " + operation + 
                " (must be one of: uppercase, lowercase, reverse, trim)"
            );
        }
    }
}
