package controller

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/shirou/gopsutil/v4/cpu"
	"github.com/shirou/gopsutil/v4/disk"
	"github.com/shirou/gopsutil/v4/host"
	"github.com/shirou/gopsutil/v4/load"
	"github.com/shirou/gopsutil/v4/mem"
)

type SystemInfo struct {
	CPUUsage       float64         `json:"cpu_usage"`
	MemoryUsage    float64         `json:"memory_usage"`
	DiskUsage      float64         `json:"disk_usage"`
	LoadAvg        float64         `json:"load_avg"`
	CPUCores       int             `json:"cpu_cores"`
	CPUMHz         float64         `json:"cpu_mhz"`
	MemoryTotal    uint64          `json:"memory_total"`
	MemoryFree     uint64          `json:"memory_free"`
	DiskPartitions []DiskPartition `json:"disk_partitions"`
	Uptime         uint64          `json:"uptime"`
}

type DiskPartition struct {
	Mountpoint  string  `json:"mountpoint"`
	Total       uint64  `json:"total"`
	Used        uint64  `json:"used"`
	UsedPercent float64 `json:"used_percent"`
}

func getSystemInfo() (SystemInfo, error) {
	var info SystemInfo

	// CPU 使用率
	cpuPercent, err := cpu.Percent(time.Second, false)
	if err == nil && len(cpuPercent) > 0 {
		info.CPUUsage = cpuPercent[0]
	}

	// CPU 详细信息
	cpuInfo, err := cpu.Info()
	if err == nil && len(cpuInfo) > 0 {
		info.CPUCores = int(cpuInfo[0].Cores)
		info.CPUMHz = cpuInfo[0].Mhz
	}

	// 内存信息
	vm, err := mem.VirtualMemory()
	if err == nil {
		info.MemoryUsage = vm.UsedPercent
		info.MemoryTotal = vm.Total
		info.MemoryFree = vm.Free
	}

	// 磁盘使用率（根目录）
	diskUsage, err := disk.Usage("/")
	if err == nil {
		info.DiskUsage = diskUsage.UsedPercent
	}

	// 磁盘分区信息
	partitions, err := disk.Partitions(false)
	if err == nil {
		for _, p := range partitions {
			usage, err := disk.Usage(p.Mountpoint)
			if err == nil {
				info.DiskPartitions = append(info.DiskPartitions, DiskPartition{
					Mountpoint:  p.Mountpoint,
					Total:       usage.Total,
					Used:        usage.Used,
					UsedPercent: usage.UsedPercent,
				})
			}
		}
	}

	// 系统负载
	loadAvg, err := load.Avg()
	if err == nil {
		info.LoadAvg = loadAvg.Load1
	}

	// 系统运行时间
	uptime, err := host.Uptime()
	if err == nil {
		info.Uptime = uptime
	}

	return info, nil
}

func SystemInfoHandle(c *gin.Context) error {
	info, err := getSystemInfo()
	if err != nil {
		return err
	}
	
	c.JSON(http.StatusOK, info)

	return nil
}
