//go:build darwin

package stats

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

func (r *Reporter) memoryStatus() (total, avail uint64) {
	out, err := exec.Command("sysctl", "-n", "hw.memsize").Output()
	if err != nil {
		return 0, 0
	}
	total, _ = strconv.ParseUint(strings.TrimSpace(string(out)), 10, 64)
	out, err = exec.Command("vm_stat").Output()
	if err != nil {
		return total, total / 2
	}
	avail = parseVmStatFreeBytes(string(out))
	return total, avail
}

func parseVmStatFreeBytes(out string) uint64 {
	const pageSize uint64 = 4096
	return parseVmStatFreePages(out) * pageSize
}

func parseVmStatFreePages(out string) uint64 {
	for _, line := range strings.Split(out, "\n") {
		if strings.Contains(line, "Pages free") {
			parts := strings.Fields(line)
			if len(parts) >= 3 {
				v, _ := strconv.ParseUint(strings.Trim(parts[2], "."), 10, 64)
				return v
			}
		}
	}
	return 0
}
