package main

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

// Go HTTP客户端节点请求结构
type GoHttpClientRequest struct {
	Context map[string]interface{} `json:"context"`
	Inputs  map[string]interface{} `json:"inputs"`
	Config  map[string]interface{} `json:"config"`
}

// Go HTTP客户端节点响应结构
type GoHttpClientResponse 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 GoHttpClientRequest
	json.NewDecoder(os.Stdin).Decode(&req)
	
	result := execute(req.Context, req.Inputs, req.Config)
	
	output, _ := json.Marshal(result)
	fmt.Println(string(output))
}

// Go HTTP客户端节点执行函数
func execute(context, inputs, config map[string]interface{}) GoHttpClientResponse {
	// 获取配置参数
	url, ok := config["url"].(string)
	if !ok || url == "" {
		return GoHttpClientResponse{
			Success: false,
			Error:   "缺少URL配置",
		}
	}
	
	method, ok := config["method"].(string)
	if !ok {
		method = "GET"
	}
	
	timeout, ok := config["timeout"].(float64)
	if !ok {
		timeout = 30
	}
	
	// 准备请求数据
	var requestBody []byte
	if data, exists := inputs["data"]; exists {
		if jsonData, err := json.Marshal(data); err == nil {
			requestBody = jsonData
		}
	}
	
	// 创建HTTP客户端
	client := &http.Client{
		Timeout: time.Duration(timeout) * time.Second,
	}
	
	// 创建请求
	req, err := http.NewRequest(method, url, bytes.NewBuffer(requestBody))
	if err != nil {
		return GoHttpClientResponse{
			Success: false,
			Error:   fmt.Sprintf("创建请求失败: %v", err),
		}
	}
	
	// 设置请求头
	if headers, ok := config["headers"].(map[string]interface{}); ok {
		for key, value := range headers {
			if strValue, ok := value.(string); ok {
				req.Header.Set(key, strValue)
			}
		}
	}
	
	// 设置默认Content-Type
	if req.Header.Get("Content-Type") == "" && requestBody != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	
	// 执行请求
	startTime := time.Now()
	resp, err := client.Do(req)
	if err != nil {
		return GoHttpClientResponse{
			Success: false,
			Error:   fmt.Sprintf("请求执行失败: %v", err),
		}
	}
	defer resp.Body.Close()
	
	// 读取响应
	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return GoHttpClientResponse{
			Success: false,
			Error:   fmt.Sprintf("读取响应失败: %v", err),
		}
	}
	
	// 尝试解析JSON响应
	var jsonResponse interface{}
	if err := json.Unmarshal(responseBody, &jsonResponse); err != nil {
		// 如果不是JSON，直接返回字符串
		jsonResponse = string(responseBody)
	}
	
	duration := time.Since(startTime)
	
	return GoHttpClientResponse{
		Success: true,
		Output:  "Go HTTP请求完成",
		Result: map[string]interface{}{
			"url":           url,
			"method":        method,
			"status_code":   resp.StatusCode,
			"response":      jsonResponse,
			"headers":       resp.Header,
			"duration_ms":   duration.Milliseconds(),
			"language":      "go",
			"performance":   "high",
		},
	}
}
