package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"sync"
	"time"
)

// Go并发任务调度节点请求结构
type GoConcurrentTasksRequest struct {
	Context map[string]interface{} `json:"context"`
	Inputs  map[string]interface{} `json:"inputs"`
	Config  map[string]interface{} `json:"config"`
}

// Go并发任务调度节点响应结构
type GoConcurrentTasksResponse struct {
	Success bool                   `json:"success"`
	Output  string                 `json:"output,omitempty"`
	Result  map[string]interface{} `json:"result,omitempty"`
	Error   string                 `json:"error,omitempty"`
}

// 任务结果结构
type TaskResult struct {
	TaskID    string      `json:"task_id"`
	Success   bool        `json:"success"`
	Result    interface{} `json:"result"`
	Error     string      `json:"error"`
	Duration  int64       `json:"duration_ms"`
}

func main() {
	var req GoConcurrentTasksRequest
	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{}) GoConcurrentTasksResponse {
	// 获取配置参数
	tasks, ok := config["tasks"].([]interface{})
	if !ok {
		return GoConcurrentTasksResponse{
			Success: false,
			Error:   "缺少任务列表配置",
		}
	}
	
	maxConcurrency, ok := config["max_concurrency"].(float64)
	if !ok {
		maxConcurrency = 10 // 默认最大并发数
	}
	
	timeout, ok := config["timeout"].(float64)
	if !ok {
		timeout = 30 // 默认超时30秒
	}
	
	// 创建并发控制
	semaphore := make(chan struct{}, int(maxConcurrency))
	var wg sync.WaitGroup
	var mu sync.Mutex
	var results []TaskResult
	
	// 并发执行任务
	for i, taskInterface := range tasks {
		task, ok := taskInterface.(map[string]interface{})
		if !ok {
			continue
		}
		
		wg.Add(1)
		go func(taskID int, task map[string]interface{}) {
			defer wg.Done()
			
			// 获取信号量
			semaphore <- struct{}{}
			defer func() { <-semaphore }()
			
			// 执行任务
			result := executeTask(taskID, task, timeout)
			
			// 线程安全地添加结果
			mu.Lock()
			results = append(results, result)
			mu.Unlock()
		}(i, task)
	}
	
	// 等待所有任务完成
	wg.Wait()
	
	// 统计结果
	successCount := 0
	failureCount := 0
	totalDuration := int64(0)
	
	for _, result := range results {
		if result.Success {
			successCount++
		} else {
			failureCount++
		}
		totalDuration += result.Duration
	}
	
	return GoConcurrentTasksResponse{
		Success: true,
		Output:  fmt.Sprintf("并发任务执行完成: 成功%d个, 失败%d个", successCount, failureCount),
		Result: map[string]interface{}{
			"total_tasks":      len(tasks),
			"success_count":   successCount,
			"failure_count":   failureCount,
			"total_duration":  totalDuration,
			"avg_duration":    float64(totalDuration) / float64(len(results)),
			"max_concurrency": maxConcurrency,
			"results":         results,
			"language":        "go",
			"performance":     "high",
		},
	}
}

// 执行单个任务
func executeTask(taskID int, task map[string]interface{}, timeout float64) TaskResult {
	startTime := time.Now()
	
	taskType, ok := task["type"].(string)
	if !ok {
		return TaskResult{
			TaskID:   fmt.Sprintf("task_%d", taskID),
			Success:  false,
			Error:    "任务类型未指定",
			Duration: time.Since(startTime).Milliseconds(),
		}
	}
	
	var result interface{}
	var err error
	
	switch taskType {
	case "http_request":
		result, err = executeHTTPTask(task)
	case "data_processing":
		result, err = executeDataProcessingTask(task)
	case "file_operation":
		result, err = executeFileOperationTask(task)
	case "sleep":
		result, err = executeSleepTask(task)
	default:
		err = fmt.Errorf("不支持的任务类型: %s", taskType)
	}
	
	duration := time.Since(startTime).Milliseconds()
	
	if err != nil {
		return TaskResult{
			TaskID:   fmt.Sprintf("task_%d", taskID),
			Success:  false,
			Error:    err.Error(),
			Duration: duration,
		}
	}
	
	return TaskResult{
		TaskID:   fmt.Sprintf("task_%d", taskID),
		Success:  true,
		Result:   result,
		Duration: duration,
	}
}

// HTTP请求任务
func executeHTTPTask(task map[string]interface{}) (interface{}, error) {
	url, ok := task["url"].(string)
	if !ok {
		return nil, fmt.Errorf("缺少URL参数")
	}
	
	method, ok := task["method"].(string)
	if !ok {
		method = "GET"
	}
	
	client := &http.Client{Timeout: 10 * time.Second}
	req, err := http.NewRequest(method, url, nil)
	if err != nil {
		return nil, err
	}
	
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	
	return map[string]interface{}{
		"status_code": resp.StatusCode,
		"url":         url,
		"method":      method,
	}, nil
}

// 数据处理任务
func executeDataProcessingTask(task map[string]interface{}) (interface{}, error) {
	data, ok := task["data"].([]interface{})
	if !ok {
		return nil, fmt.Errorf("缺少数据参数")
	}
	
	operation, ok := task["operation"].(string)
	if !ok {
		operation = "count"
	}
	
	var result interface{}
	switch operation {
	case "count":
		result = len(data)
	case "sum":
		sum := 0.0
		for _, item := range data {
			if num, ok := item.(float64); ok {
				sum += num
			}
		}
		result = sum
	case "reverse":
		reversed := make([]interface{}, len(data))
		for i, item := range data {
			reversed[len(data)-1-i] = item
		}
		result = reversed
	default:
		return nil, fmt.Errorf("不支持的操作: %s", operation)
	}
	
	return map[string]interface{}{
		"operation": operation,
		"result":    result,
		"count":     len(data),
	}, nil
}

// 文件操作任务
func executeFileOperationTask(task map[string]interface{}) (interface{}, error) {
	operation, ok := task["operation"].(string)
	if !ok {
		return nil, fmt.Errorf("缺少操作类型")
	}
	
	switch operation {
	case "list_directory":
		path, ok := task["path"].(string)
		if !ok {
			return nil, fmt.Errorf("缺少路径参数")
		}
		
		// 模拟目录列表
		return map[string]interface{}{
			"operation": "list_directory",
			"path":      path,
			"files":     []string{"file1.txt", "file2.txt", "file3.txt"},
		}, nil
		
	case "file_info":
		filename, ok := task["filename"].(string)
		if !ok {
			return nil, fmt.Errorf("缺少文件名参数")
		}
		
		return map[string]interface{}{
			"operation": "file_info",
			"filename":  filename,
			"size":      1024,
			"modified":  time.Now().Format(time.RFC3339),
		}, nil
		
	default:
		return nil, fmt.Errorf("不支持的文件操作: %s", operation)
	}
}

// 睡眠任务（用于测试）
func executeSleepTask(task map[string]interface{}) (interface{}, error) {
	duration, ok := task["duration"].(float64)
	if !ok {
		duration = 1.0
	}
	
	time.Sleep(time.Duration(duration) * time.Second)
	
	return map[string]interface{}{
		"operation": "sleep",
		"duration":  duration,
	}, nil
}
