local data = mw.loadData("Module:utilities/format_categories/data")

return function(categories, lang, sort_key, sort_base, force_output, sc)
	if type(lang) == "table" and not lang.getCode then
		error("The second argument to format_categories should be a language object.")
	end

	local title_obj = mw.title.getCurrentTitle()	

	if force_output or data.allowedNamespaces[title_obj.nsText] or data.allowedPrefixedPages[title_obj.prefixedText] then
		local PAGENAME = title_obj.text
		local SUBPAGENAME = title_obj.subpageText
		
		if not lang then
			lang = require("Module:languages").getByCode("und")
		end
		
		-- Generate a default sort key
		sort_base = lang:makeSortKey(sort_base or SUBPAGENAME, sc)
		
		if sort_key and sort_key ~= "" then
			-- Gather some statistics regarding sort keys
			if mw.ustring.upper(sort_key) == sort_base then
				table.insert(categories, "Sort key tracking/redundant")
			end
		else
			sort_key = sort_base
		end
		
		-- If the sortkey is empty, remove it.
		-- Leave the sortkey if it is equal to PAGENAME, because it still
		-- might be different from DEFAULTSORT and therefore have an effect; see
		-- [[Wiktionary:Grease pit/2020/April#Module:utilities#format categories]].
		if sort_key == "" then
			sort_key = nil
		end
		
		local out_categories = {}
		for key, cat in ipairs(categories) do
			out_categories[key] = "[[Category:" .. cat .. (sort_key and "|" .. sort_key or "") .. "]]"
		end
		
		return table.concat(out_categories, "")
	else
		return ""
	end
end