package collector

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

// AgentCollector Agent采集器
 type AgentCollector struct {
	agentURL string
	client   *http.Client
}

// AgentMetrics Agent返回的监控指标
 type AgentMetrics struct {
	CPU    float64 `json:"cpu"`
	Memory float64 `json:"memory"`
	Disk   float64 `json:"disk"`
	Network struct {
		BytesSent     uint64 `json:"bytes_sent"`
		BytesReceived uint64 `json:"bytes_received"`
	} `json:"network"`
}

// NewAgentCollector 创建新的Agent采集器
func NewAgentCollector(agentURL string) *AgentCollector {
	return &AgentCollector{
		agentURL: agentURL,
		client: &http.Client{
			Timeout: 10 * time.Second,
		},
	}
}

// GetMetrics 获取Agent监控指标
func (c *AgentCollector) GetMetrics() (*AgentMetrics, error) {
	// 发送HTTP请求到Agent
	resp, err := c.client.Get(fmt.Sprintf("%s/metrics", c.agentURL))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("agent returned status code %d", resp.StatusCode)
	}

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	// 解析JSON响应
	var metrics AgentMetrics
	if err := json.Unmarshal(body, &metrics); err != nil {
		return nil, err
	}

	return &metrics, nil
}

// GetCPUUsage 获取CPU使用率
func (c *AgentCollector) GetCPUUsage() (float64, error) {
	metrics, err := c.GetMetrics()
	if err != nil {
		return 0, err
	}

	return metrics.CPU, nil
}

// GetMemoryUsage 获取内存使用率
func (c *AgentCollector) GetMemoryUsage() (float64, error) {
	metrics, err := c.GetMetrics()
	if err != nil {
		return 0, err
	}

	return metrics.Memory, nil
}

// GetDiskUsage 获取磁盘使用率
func (c *AgentCollector) GetDiskUsage(partition string) (float64, error) {
	metrics, err := c.GetMetrics()
	if err != nil {
		return 0, err
	}

	// 目前Agent只返回整体磁盘使用率，忽略partition参数
	return metrics.Disk, nil
}
