-- ROBLOX deviation predefine variables

local getMatchingKeyPaths, replaceKeyPathWithValue, getPath

export type Template = Record<string, any>
export type Templates = Array<Template>
export type Headings = Array<string>

local function interpolateVariables(title: string, template: Template, index: number): string
	return Array.reduce(
		Array.reduce(Object.keys(template), getMatchingKeyPaths(title), {}), -- aka flatMap
		replaceKeyPathWithValue(template),
		title
	):gsub(
		"%$#", -- ROBLOX deviation: escaped string
		tostring(index),
		1
	)
end
exports.interpolateVariables = interpolateVariables

function getMatchingKeyPaths(title: string)
	return function(matches: Headings, key: string)
		return Array.concat(
			matches,
			(function()
				local ref = {}
				for match in title:gmatch(("%%$%s[%%.%%w]*"):format(key)) do -- ROBLOX deviation: escape characters
					table.insert(ref, match)
				end
				return ref
			end)()
		)
	end
end

function replaceKeyPathWithValue(template: Template): (title: string, match: string) -> string
	return function(title: string, match: string)
		local newMatch = match:gsub("%$", "", 1) -- ROBLOX deviation: escape string
		local keyPath = String.split(newMatch, "%.") -- ROBLOX deviation: escape string
		local value = getPath(template, keyPath)
		if isPrimitive(value) then
			return title:gsub(match, tostring(value), 1)
		end
		return title:gsub(match, pretty(value, { maxDepth = 1, min = true }), 1)
	end
end
