local lib = ...
local dbg = {
	aloud = false;
}

local lastmod, lastarea

function dbg.debugger(area)
	local depth = 0
	local d = {}
	function d.enter() depth = depth+1 end
	function d.exit() depth = depth-1 end
	local mod = minetest.get_current_modname()
	if dbg.aloud then
		function d.report(fmt, ...)
			local where = debug.getinfo(2)
			local caller = debug.getinfo(3)
			if mod and (lastmod ~= mod or lastarea ~= area) then
				local ms = mod or ''
				if area then ms = ms .. '.' .. area end
				print(string.format('\27[1mmodule \27[31m%s\27[m\n%s', ms, string.rep('-', #ms + 7)))
				lastmod, lastarea = mod, area
			end
			local callsource = string.format('%s:%s', caller.name, caller.currentline)
			if caller.source ~= where.source then
				callsource = callsource .. caller.source
			end
			print(
				string.rep('  ', depth) ..
				string.format(
					'> \27[1m%s:%s\27[m ← \27[34m%s\27[m :: %s',
					where.name, where.currentline,
					callsource,
					string.format(fmt, ...)
				)
			)
		end
		function d.wrap(fn)
			return function(...)
				d.enter()
				local ret = {fn(...)}
				d.exit()
				return (table.unpack or unpack)(ret)
			end
		end
	else
		function d.report() end
		function d.wrap(fn) return fn end
	end
	return d
end

return dbg