package collector

import (
	"os/exec"
	"strconv"
	"strings"
)

type DiskInfo struct {
	Filesystem string `json:"filesystem"`
	TotalBytes int64  `json:"total_bytes"`
	UsedBytes  int64  `json:"used_bytes"`
	FreeBytes  int64  `json:"free_bytes"`
	MountPoint string `json:"mount_point"`
}

func CollectDisks() []DiskInfo {
	// df -k (1K-Bloecke) fuer einfacheres Parsen
	out, err := exec.Command("df", "-k", "-t", "ufs,zfs").Output()
	if err != nil {
		// Fallback ohne Typ-Filter
		out, err = exec.Command("df", "-k").Output()
		if err != nil {
			return nil
		}
	}

	var disks []DiskInfo
	lines := strings.Split(strings.TrimSpace(string(out)), "\n")

	for i, line := range lines {
		if i == 0 {
			continue // Header ueberspringen
		}

		fields := strings.Fields(line)
		if len(fields) < 6 {
			continue
		}

		// Pseudo-Filesysteme ueberspringen
		fs := fields[0]
		mount := fields[len(fields)-1]
		if strings.HasPrefix(fs, "devfs") || strings.HasPrefix(fs, "tmpfs") || fs == "fdescfs" || fs == "procfs" {
			continue
		}

		total, _ := strconv.ParseInt(fields[1], 10, 64)
		used, _ := strconv.ParseInt(fields[2], 10, 64)
		avail, _ := strconv.ParseInt(fields[3], 10, 64)

		disks = append(disks, DiskInfo{
			Filesystem: fs,
			TotalBytes: total * 1024,
			UsedBytes:  used * 1024,
			FreeBytes:  avail * 1024,
			MountPoint: mount,
		})
	}

	return disks
}
