-- lx-bundle:true

--- Format byte counts for compact labels and complete descriptions
-- @module core.format.bytes

local bytes = {}

--- Return one safe whole-byte count
-- @param value number|nil raw byte count
-- @return integer normalized byte count
local function normalize(value)
	return math.max(0, math.floor((tonumber(value) or 0) + 0.5))
end

--- Format bytes as the compact decimal-unit label used by space-limited interfaces
-- @param value number|nil raw byte count
-- @return string compact byte label
function bytes.short(value)
	value = normalize(value)

	if value < 1000 then
		return string.format("%d B", value)
	elseif value < 100000 then
		return string.format("%.1f kB", value / 1000)
	elseif value < 1000000 then
		return string.format("%.0f kB", value / 1000)
	elseif value < 100000000 then
		return string.format("%.2f MB", value / 1000000)
	elseif value < 1000000000 then
		return string.format("%.1f MB", value / 1000000)
	end

	return string.format("%.0f MB", value / 1000000)
end

--- Format a complete byte count with readable thousands separators
-- @param value number|nil raw byte count
-- @return string complete byte description
function bytes.full(value)
	value = normalize(value)
	local groups = {}

	repeat
		groups[#groups + 1] = value % 1000
		value = math.floor(value / 1000)
	until value == 0

	local text = tostring(groups[#groups])
	for index = #groups - 1, 1, -1 do
		text = text .. string.format(",%03d", groups[index])
	end

	return text .. " Bytes"
end

return bytes
