-- lx-bundle:true

local format = {}

-- Lua doubles have 53 bits of precision
local POW2_64 = 18446744073709551616.0 -- 2^64 as double
local tostring = tostring

--- Fast unsigned formatter (signed int64 to unsigned int64 string)
-- Useful when Lua represents uint64 values as negative signed integers
-- @param i64 integer Signed 64-bit integer value
-- @return string Unsigned decimal string representation
function format.i64_to_u64_string(i64)
	if i64 < 0 then
		--- Wrap negative signed value into the uint64 range
		return tostring(i64 + POW2_64)
	else
		return tostring(i64)
	end
end

function iif( cond, T, F )
	if cond then return T else return F end
end

--- Format a Lua value into a readable multi-line dump string
-- Tables are expanded recursively with indentation and basic cycle protection
-- Strings are quoted with single quotes, other values use tostring
-- @param var any Value to dump
-- @return table Dumped representation as lines
function format.dump_to_table(var, indent, done)
	done = done or {}
	indent = indent or 0

	local spaces = string.rep(" ", indent)
	local out = {}

	if type(var) == "table" then
		for k, v in pairs(var) do
			--- Prefix each entry with current indentation
			out[#out + 1] = spaces

			if type(v) == "table" and not done[v] then
				--- Mark table to avoid infinite recursion on cycles
				done[v] = true

				out[#out + 1] = "[" .. tostring(k) .. "] =\n"
				out[#out + 1] = spaces .. "(\n"
				out[#out + 1] = format.dump_to_table(v, indent + indent, done)
				out[#out + 1] = spaces .. ")\n"

			elseif type(v) == "string" then
				--- Quote strings to keep output unambiguous
				out[#out + 1] = "[" .. tostring(k) .. "] = '" .. tostring(v) .. "'\n"

			else
				out[#out + 1] = "[" .. tostring(k) .. "] = " .. tostring(v) .. "\n"
			end
		end
	else
		out[#out + 1] = tostring(var) .. "\n"
	end
	return out
end

--- Dump a Lua value to a formatted string
-- @param var any Value to dump
-- @return string Dumped representation
function format.dump(var,indent)
	indent = indent or 4
	text = table.concat(format.dump_to_table(var, indent))
	return "(\n" .. text .. ")\n"
end

return format
