-- factoryos.drivers.energy — generic energy_storage peripheral driver.
-- Covers any block exposing Forge energy caps (Mekanism cubes, etc.).
-- NOTE: Forge exposes no throughput; callers derive rates from samples.

local M = {}

--- Discover all energy_storage peripherals. Returns [{name, p}].
function M.discover()
  local out = {}
  for _, p in ipairs({ peripheral.find("energy_storage") }) do
    local name = peripheral.getName and peripheral.getName(p) or "?"
    out[#out + 1] = { name = name, p = p }
  end
  table.sort(out, function(a, b) return a.name < b.name end)
  return out
end

--- Sample a list of units (from discover). Never throws: a failed unit
--- reports stored/capacity as nil so callers can mark quality.
function M.sample(units)
  local res = { ts = os.epoch and os.epoch("utc") or 0, units = {} }
  for _, u in ipairs(units) do
    local okE, e = pcall(u.p.getEnergy)
    local okC, c = pcall(u.p.getEnergyCapacity)
    res.units[#res.units + 1] = {
      name = u.name,
      stored = okE and e or nil,
      cap    = okC and c or nil,
      ok = okE and okC,
    }
  end
  return res
end

return M
