package system

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

// CoreUsage holds the usage percentage for a single logical core, computed as
// the delta of non-idle ticks over total ticks between two /proc/stat reads.
type CoreUsage struct {
	Core      int     `json:"core" example:"0" doc:"Logical core index"`
	UsagePct  float64 `json:"usage_pct" example:"23.4" doc:"Usage percentage (0–100)"`
}

type LoadInfo struct {
	Load1    float64     `json:"load1" example:"0.42"`
	Load5    float64     `json:"load5" example:"0.55"`
	Load15   float64     `json:"load15" example:"0.61"`
	CPUUsage []CoreUsage `json:"cpu_usage" doc:"Per-core CPU usage percentage (sampled over ~1 s); empty until the first sample completes"`
}

func loadInfo(sampler *Sampler) LoadInfo {
	data, _ := os.ReadFile("/proc/loadavg")
	l := parseLoadavg(string(data))
	l.CPUUsage = sampler.Snapshot()
	return l
}

func parseLoadavg(loadavg string) LoadInfo {
	f := strings.Fields(loadavg)
	if len(f) < 3 {
		return LoadInfo{}
	}
	at := func(i int) float64 { v, _ := strconv.ParseFloat(f[i], 64); return v }
	return LoadInfo{Load1: at(0), Load5: at(1), Load15: at(2)}
}
