package service

import (
	"runtime"
	"time"

	"kra/internal/service/dto"

	"github.com/shirou/gopsutil/v4/cpu"
	"github.com/shirou/gopsutil/v4/disk"
	"github.com/shirou/gopsutil/v4/mem"
)

func (s *SystemConfigService) ServerInfo() (*dto.ServerInfoResponse, error) {
	physicalCores, err := cpu.Counts(false)
	if err != nil {
		return nil, err
	}
	cpuPercent, err := cpu.Percent(200*time.Millisecond, true)
	if err != nil {
		return nil, err
	}
	memory, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}
	diskInfo := make([]dto.ServerDiskResponse, 0)
	for _, mountPoint := range s.DiskMountPoints() {
		usage, usageErr := disk.Usage(mountPoint)
		if usageErr != nil {
			return nil, usageErr
		}
		diskInfo = append(diskInfo, dto.ServerDiskResponse{MountPoint: mountPoint, UsedMB: usage.Used / 1024 / 1024, UsedGB: usage.Used / 1024 / 1024 / 1024, TotalMB: usage.Total / 1024 / 1024, TotalGB: usage.Total / 1024 / 1024 / 1024, UsedPercent: int(usage.UsedPercent)})
	}
	usedMB, totalMB := memory.Used/1024/1024, memory.Total/1024/1024
	return &dto.ServerInfoResponse{
		OS:   dto.ServerOSResponse{GOOS: runtime.GOOS, NumCPU: runtime.NumCPU(), Compiler: runtime.Compiler, GoVersion: runtime.Version(), NumGoroutine: runtime.NumGoroutine()},
		CPU:  dto.ServerCPUResponse{CPUs: cpuPercent, Cores: physicalCores},
		RAM:  dto.ServerRAMResponse{UsedMB: usedMB, TotalMB: totalMB, UsedPercent: int(memory.UsedPercent)},
		Disk: diskInfo,
	}, nil
}
