package collector

import (
	"os"
	"strconv"
	"strings"
)

type MemoryInfo struct {
	TotalBytes int64
	UsedBytes  int64
	FreeBytes  int64
}

func CollectMemory() MemoryInfo {
	mem := MemoryInfo{}
	
	data, err := os.ReadFile("/proc/meminfo")
	if err != nil {
		return mem
	}
	
	lines := strings.Split(string(data), "\n")
	values := make(map[string]int64)
	
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		
		parts := strings.Fields(line)
		if len(parts) < 2 {
			continue
		}
		
		key := strings.TrimSuffix(parts[0], ":")
		valueStr := parts[1]
		
		// Wert in kB, konvertiere zu Bytes
		if value, err := strconv.ParseInt(valueStr, 10, 64); err == nil {
			values[key] = value * 1024 // kB zu Bytes
		}
	}
	
	// Basis-Werte
	memTotal := values["MemTotal"]
	memFree := values["MemFree"]
	memAvailable := values["MemAvailable"]
	buffers := values["Buffers"]
	cached := values["Cached"]
	
	mem.TotalBytes = memTotal
	
	// Verfügbarer Speicher: Nutze MemAvailable falls vorhanden, sonst berechne
	if memAvailable > 0 {
		mem.FreeBytes = memAvailable
	} else {
		// Fallback: Free + Buffers + Cached (grobe Schätzung)
		mem.FreeBytes = memFree + buffers + cached
	}
	
	// Benutzter Speicher = Total - Free
	if mem.FreeBytes > mem.TotalBytes {
		mem.FreeBytes = mem.TotalBytes
	}
	mem.UsedBytes = mem.TotalBytes - mem.FreeBytes
	
	return mem
}