package host_info

import (
	"agent-wdd/log"
	"bufio"
	"os"
	"path/filepath"
	"strings"
)

var CommonDiskPath = []string{
	"/",
	"/var",
	"/var/lib/docker",
	"/home",
	"/user",
	"var/log",
}

func CheckCommonMounts() (map[string]bool, error) {
	// 读取/proc/mounts获取所有挂载点
	file, err := os.Open("/proc/mounts")
	if err != nil {
		return nil, err
	}
	defer file.Close()

	mountPoints := make(map[string]bool)
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fields := strings.Fields(line)
		if len(fields) < 2 {
			continue
		}
		mountPoint := filepath.Clean(fields[1])
		mountPoints[mountPoint] = true
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return mountPoints, err
}

func DiskListGather() {

	log.Info("Gathering INFO => DISK !")

	var diskList []Disk

	// 拿到所有挂载点
	mountPoints, _ := CheckCommonMounts()

	// 常用目录
	for _, diskPath := range CommonDiskPath {
		// 转换为绝对路径并标准化
		absPath, err := filepath.Abs(diskPath)
		if err != nil {
			// 处理错误，例如路径无效，这里选择跳过
			continue
		}
		cleanPath := filepath.Clean(absPath)
		if mountPoints[cleanPath] {
			// 挂载点存在，计算使用情况

			disk := Disk{Path: cleanPath}
			disk.calculateDiskUsage()
			diskList = append(diskList, disk)
		}

	}

	// 赋值回去
	ConfigCache.Agent.Disks = diskList

	//utils.BeautifulPrint(diskList)
}

// 计算磁盘使用情况
func (disk *Disk) calculateDiskUsage() {
	// var stat syscall.Statfs_t
	// err := syscall.Statfs(disk.Path, &stat)
	// if err != nil {
	// 	log.Error("disk syscall error: %v", err)
	// 	disk.Size = "0B"
	// 	disk.Usage = "0B"
	// 	disk.Percent = "0.00%"
	// 	return
	// }

	// // 计算存储空间大小
	// totalBytes := stat.Blocks * uint64(stat.Bsize)
	// availBytes := stat.Bavail * uint64(stat.Bsize)
	// usedBytes := totalBytes - availBytes

	// // 格式化输出
	// disk.Size = utils.HumanDiskSize(totalBytes)
	// disk.Usage = utils.HumanDiskSize(usedBytes)

	// if totalBytes == 0 {
	// 	disk.Percent = "0.00%"
	// } else {
	// 	percent := float64(usedBytes) / float64(totalBytes) * 100
	// 	disk.Percent = fmt.Sprintf("%.2f%%", percent)
	// }
}

func DiskListSaveConfig() {
	log.Info("Saving INFO => DISK !")

	SaveConfig()
}
