local nk = { }
local wiki_entries = { }

local function processStatFile(name, changeOutLocation)
	--ConPrintf("Processing File: '%s'", name)
	local statDescriptor = { }
	local curLang
	local curDescriptor = { }
	local prepend = ''
	local function processLine(line)
		if prepend then
			line = prepend .. line
			prepend = ''
		end
		local parent = line:match('include "Metadata/StatDescriptions/(.+)%.csd"$')
		if parent then
			statDescriptor.parent = parent:gsub("/statset", "_statset")
			return
		end
		local noDesc = line:match("no_description ([%w_%+%-%%]+)")
		if noDesc then
			table.insert(statDescriptor, { stats = { noDesc } })
			statDescriptor[noDesc] = #statDescriptor
		elseif line:match("handed_description") or (line:match("description") and not line:match("_description")) then	
			local name = line:match("description ([%w_]+)")
			curLang = { }
			curDescriptor = { curLang, order = order, name = name }
			table.insert(statDescriptor, curDescriptor)
		elseif not curDescriptor.stats then
			local stats = line:match("%d+%s+([%w_%+%-%% ]+)")
			if stats then
				curDescriptor.stats = { }
				for stat in stats:gmatch("[%w_%+%-%%]+") do
					table.insert(curDescriptor.stats, stat)
					statDescriptor[stat] = #statDescriptor
				end
			else -- Try to combine it with the next line
				prepend = line
			end
		else
			local langName = line:match('lang "(.+)"')
			if langName then
				curLang = nil--{ }
				--curDescriptor.lang[langName] = curLang
			elseif curLang then
				local table_only = false
				if line:match('table_only') then
					line = line:gsub('table_only ', '')
					table_only = true
				end
				local statLimits, text, special = line:match('([%d%-#!| ]+)%s*"(.-)"%s*(.*)')
				if statLimits then
					if text and table_only then
						text = text:gsub('@', ' ')
					end
					local desc = { text = escapeGGGString(text):gsub("\\([^nb])", "\\n%1"), limit = { } }
					for statLimit in statLimits:gmatch("[!%d%-#|]+") do
						local limit = { }
						
						if statLimit == "#" then
							limit[1] = "#"
							limit[2] = "#"
						elseif statLimit:match("^%-?%d+$") then
							limit[1] = tonumber(statLimit)
							limit[2] = tonumber(statLimit)
						else
							local negate = statLimit:match("^!(-?%d+)$")
							if negate then
								limit[1] = "!"
								limit[2] = tonumber(negate)
							else
								limit[1], limit[2] = statLimit:match("([%d%-#]+)|([%d%-#]+)")
								limit[1] = tonumber(limit[1]) or limit[1]
								limit[2] = tonumber(limit[2]) or limit[2]
							end
						end
						table.insert(desc.limit, limit)
					end
					for k, v in special:gmatch("([%w%%_]+) (%d+)") do
						table.insert(desc, {
							k = k,
							v = tonumber(v) or v,
						})
						nk[k] = v
					end
					if special:match("canonical_line") then
						table.insert(desc, {
							k = "canonical_line",
							v = true,
						})
						nk["canonical_line"] = true
					end
					table.insert(curLang, desc)
				end
			end
		end
	end

	local text = convertUTF16to8(getFile("Metadata/StatDescriptions/"..name..".csd"))
	for line in text:gmatch("[^\r\n]+") do
		processLine(line)
	end
	local out = nil
	if changeOutLocation then
		out = io.open("../Data/StatDescriptions/Specific_Skill_Stat_Descriptions/"..name:gsub("specific_skill_stat_descriptions/", ""):gsub("/", "_")..".lua", "w")
	else
		out = io.open("../Data/StatDescriptions/"..name..".lua", "w")
	end
	out:write('-- This file is automatically generated, do not edit!\n')
	out:write('-- Item data (c) Grinding Gear Games\n\nreturn ')
	writeLuaTable(out, statDescriptor, 1)
	out:close()
end

local statFileList = {
	"active_skill_gem_stat_descriptions",
	"advanced_mod_stat_descriptions",
	"gem_stat_descriptions",
	"meta_gem_stat_descriptions",
	"monster_stat_descriptions",
	"passive_skill_aura_stat_descriptions",
	"passive_skill_stat_descriptions",
	"skill_stat_descriptions",
	"stat_descriptions",
	"utility_flask_buff_stat_descriptions",
}
for _, name in ipairs(statFileList) do
	processStatFile(name)
end

local handle = NewFileSearch("ggpk/Metadata/StatDescriptions/Specific_Skill_Stat_Descriptions/*.csd")
while handle do
	processStatFile("specific_skill_stat_descriptions/"..handle:GetFileName():gsub("%.csd", ""))
	if not handle:NextFile() then
		break
	end
end

local specificSkillDirectoryList = {
	"blazing_cluster",
	"bone_spike",
	"channel_stampede",
	"channelled_slam",
	"corpse_cloud",
	"earthquake",
	"gas_cloud_arrow",
	"gathering_storm",
	"herald_of_thunder",
	"ice_ambush",
	"incinerate_player",
	"lightning_arrow",
	"magnetic_salvo",
	"molten_blast",
	"new_sunder",
	"poison_vine_arrow",
	"siege_cascade_stormblast",
	"sniper_gas_shot",
	"solar_orb",
	"spike_slam",
	"tempest_bell",
	"tornado_shot",
	"toxic_grenade",
}

for _, name in ipairs(specificSkillDirectoryList) do
	local handle = NewFileSearch("ggpk/Metadata/StatDescriptions/Specific_Skill_Stat_Descriptions/"..name.."/*.csd")
	while handle do
		processStatFile("specific_skill_stat_descriptions/"..name.."/"..handle:GetFileName():gsub("%.csd", ""), true)
		if not handle:NextFile() then
			break
		end
	end
end

for k, v in pairs(nk) do
	--print("'"..k.."' = '"..v.."'")
end

print("Stat descriptions exported.")
