package main

import (
	"encoding/json"
	"fmt"
	"os"
	"sort"
	"strings"
	"time"
)

// Go数据处理节点请求结构
type GoDataProcessingRequest struct {
	Context map[string]interface{} `json:"context"`
	Inputs  map[string]interface{} `json:"inputs"`
	Config  map[string]interface{} `json:"config"`
}

// Go数据处理节点响应结构
type GoDataProcessingResponse struct {
	Success bool                   `json:"success"`
	Output  string                 `json:"output,omitempty"`
	Result  map[string]interface{} `json:"result,omitempty"`
	Error   string                 `json:"error,omitempty"`
}

func main() {
	var req GoDataProcessingRequest
	json.NewDecoder(os.Stdin).Decode(&req)
	
	result := execute(req.Context, req.Inputs, req.Config)
	
	output, _ := json.Marshal(result)
	fmt.Println(string(output))
}

// Go数据处理节点执行函数
func execute(context, inputs, config map[string]interface{}) GoDataProcessingResponse {
	// 获取配置参数
	operation, ok := config["operation"].(string)
	if !ok {
		operation = "sort"
	}
	
	data, ok := inputs["data"]
	if !ok {
		return GoDataProcessingResponse{
			Success: false,
			Error:   "缺少输入数据",
		}
	}
	
	startTime := time.Now()
	
	switch operation {
	case "sort":
		return executeSort(data)
	case "filter":
		return executeFilter(data, config)
	case "aggregate":
		return executeAggregate(data, config)
	case "transform":
		return executeTransform(data, config)
	default:
		return GoDataProcessingResponse{
			Success: false,
			Error:   fmt.Sprintf("不支持的操作: %s", operation),
		}
	}
}

// 排序操作
func executeSort(data interface{}) GoDataProcessingResponse {
	var result []interface{}
	
	switch v := data.(type) {
	case []interface{}:
		// 复制切片
		result = make([]interface{}, len(v))
		copy(result, v)
		
		// 尝试排序
		if len(result) > 0 {
			switch result[0].(type) {
			case string:
				stringSlice := make([]string, len(result))
				for i, item := range result {
					stringSlice[i] = item.(string)
				}
				sort.Strings(stringSlice)
				for i, item := range stringSlice {
					result[i] = item
				}
			case float64:
				floatSlice := make([]float64, len(result))
				for i, item := range result {
					floatSlice[i] = item.(float64)
				}
				sort.Float64s(floatSlice)
				for i, item := range floatSlice {
					result[i] = item
				}
			}
		}
	default:
		return GoDataProcessingResponse{
			Success: false,
			Error:   "数据格式不支持排序",
		}
	}
	
	return GoDataProcessingResponse{
		Success: true,
		Output:  "Go数据处理完成",
		Result: map[string]interface{}{
			"operation":     "sort",
			"processed_data": result,
			"count":         len(result),
			"language":      "go",
			"performance":   "high",
		},
	}
}

// 过滤操作
func executeFilter(data interface{}, config map[string]interface{}) GoDataProcessingResponse {
	filterValue, ok := config["filter_value"].(string)
	if !ok {
		filterValue = ""
	}
	
	var result []interface{}
	
	switch v := data.(type) {
	case []interface{}:
		for _, item := range v {
			if str, ok := item.(string); ok {
				if strings.Contains(str, filterValue) {
					result = append(result, item)
				}
			}
		}
	default:
		return GoDataProcessingResponse{
			Success: false,
			Error:   "数据格式不支持过滤",
		}
	}
	
	return GoDataProcessingResponse{
		Success: true,
		Output:  "Go数据过滤完成",
		Result: map[string]interface{}{
			"operation":      "filter",
			"filter_value":   filterValue,
			"processed_data": result,
			"count":          len(result),
			"language":       "go",
			"performance":    "high",
		},
	}
}

// 聚合操作
func executeAggregate(data interface{}, config map[string]interface{}) GoDataProcessingResponse {
	aggregateType, ok := config["aggregate_type"].(string)
	if !ok {
		aggregateType = "sum"
	}
	
	var result interface{}
	var count int
	
	switch v := data.(type) {
	case []interface{}:
		count = len(v)
		switch aggregateType {
		case "sum":
			sum := 0.0
			for _, item := range v {
				if num, ok := item.(float64); ok {
					sum += num
				}
			}
			result = sum
		case "count":
			result = len(v)
		case "avg":
			sum := 0.0
			validCount := 0
			for _, item := range v {
				if num, ok := item.(float64); ok {
					sum += num
					validCount++
				}
			}
			if validCount > 0 {
				result = sum / float64(validCount)
			} else {
				result = 0.0
			}
		}
	default:
		return GoDataProcessingResponse{
			Success: false,
			Error:   "数据格式不支持聚合",
		}
	}
	
	return GoDataProcessingResponse{
		Success: true,
		Output:  "Go数据聚合完成",
		Result: map[string]interface{}{
			"operation":     aggregateType,
			"result":        result,
			"count":         count,
			"language":      "go",
			"performance":   "high",
		},
	}
}

// 转换操作
func executeTransform(data interface{}, config map[string]interface{}) GoDataProcessingResponse {
	transformType, ok := config["transform_type"].(string)
	if !ok {
		transformType = "uppercase"
	}
	
	var result []interface{}
	
	switch v := data.(type) {
	case []interface{}:
		for _, item := range v {
			if str, ok := item.(string); ok {
				switch transformType {
				case "uppercase":
					result = append(result, strings.ToUpper(str))
				case "lowercase":
					result = append(result, strings.ToLower(str))
				case "reverse":
					runes := []rune(str)
					for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
						runes[i], runes[j] = runes[j], runes[i]
					}
					result = append(result, string(runes))
				default:
					result = append(result, str)
				}
			} else {
				result = append(result, item)
			}
		}
	default:
		return GoDataProcessingResponse{
			Success: false,
			Error:   "数据格式不支持转换",
		}
	}
	
	return GoDataProcessingResponse{
		Success: true,
		Output:  "Go数据转换完成",
		Result: map[string]interface{}{
			"operation":      "transform",
			"transform_type": transformType,
			"processed_data": result,
			"count":          len(result),
			"language":       "go",
			"performance":    "high",
		},
	}
}
