//go:build linux

package stats

import (
	"bufio"
	"io"
	"os"
	"strconv"
	"strings"
)

func (r *Reporter) memoryStatus() (total, avail uint64) {
	f, err := os.Open("/proc/meminfo")
	if err != nil {
		return 0, 0
	}
	defer f.Close()
	return parseMeminfo(f)
}

func parseMeminfo(r io.Reader) (total, avail uint64) {
	var memTotal, memAvail uint64
	sc := bufio.NewScanner(r)
	for sc.Scan() {
		line := sc.Text()
		if strings.HasPrefix(line, "MemTotal:") {
			memTotal = parseKB(line)
		} else if strings.HasPrefix(line, "MemAvailable:") {
			memAvail = parseKB(line)
		}
	}
	if memTotal == 0 {
		return 0, 0
	}
	return memTotal * 1024, memAvail * 1024
}

func parseKB(line string) uint64 {
	fields := strings.Fields(line)
	if len(fields) < 2 {
		return 0
	}
	v, _ := strconv.ParseUint(fields[1], 10, 64)
	return v
}
