local export = {}

local m_IPA = require("Module:IPA")
local lang = require("Module:languages").getByCode("huu")
local rsub = mw.ustring.gsub
local rlower = mw.ustring.lower

local V = "[aeiɨou]"
local C = "[tkbdgmnñfvzjyrpsʃ]"

local phon = {
	["t"]="t",	["k"]="k",	["b"]="b",	["d"]="d",
	["g"]="ɡ",	["m"]="m",	["n"]="n",	["ñ"]="ɲ",
	["f"]="ɸ",	["v"]="β",	["z"]="θ",
	["y"]="dʒ", ["r"]="ɾ",	["p"]="p",	["s"]="s",
	["i"]="i",	["ɨ"]="ɯ",	["u"]="u",	["e"]="ɛ",	
	["a"]="a",	["o"]="ɔ",	["'"]="ʔ"
}

local function phonetic(text)
	text = rlower(text)
	if mw.ustring.find(text, "ˈ") == nil and mw.ustring.find(text, "^-") == nil then text = "ˈ" .. text end
	text = rsub(text, "j", "h")
	-- digraphs
	text = rsub(text, "ch", "tʃ")
	text = rsub(text, "([aeu])i", "%1ji̯")
	text = rsub(text, "([ao])ɨ", "%1ɰɯ̯")
	text = rsub(text, "([aeou])ːi", "%1ːji̯")
	text = rsub(text, "([aeou])ːɨ", "%1ːɰɯ̯")
	text = rsub(text, "(" .. V .. ")%1", "%1ː")
	text = rsub(text, "u(ː?)(" .. V .. ")", "u%1w%2")
	text = rsub(text, "ˈ([kg])uw", "ˈ%1w")
	text = rsub(text, "i(ː?)(" .. V .. ")", "i%1j%2")
	text = rsub(text, "ɨ(ː?)(" .. V .. ")", "ɨ%1ɰ%2")
	text = rsub(text, "ji̯(" .. V .. ")", "j%1")
	text = rsub(text, "ɰɯ̯(" .. V .. ")", "ɰ%1")
	text = rsub(text, "ji̯", "i̯")
	text = rsub(text, "ɰɯ̯", "ɯ̯")
	-- general phonology
	text = rsub(text, ".", phon)
	-- affricates
	text = rsub(text, "tʃ", "t͡ʃ")
	text = rsub(text, "dʒ", "d͡ʒ")
	
	return text
end

function export.IPA(frame)
	local words = {}
	
	for _, word in ipairs(frame:getParent().args) do
		table.insert(words, word)
	end
	
	if #words == 0 then
		words = {mw.title.getCurrentTitle().text}
	end
	
	local IPA_results = {}
	
	for _, word in ipairs(words) do
		table.insert(IPA_results, { pron = "[" .. phonetic(word) .. "]" })
	end
	
	return m_IPA.format_IPA_full(lang, IPA_results)
end

return export