local export = {}

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

local V = "[ʌɐɑaɤeɨioɵuʉəæE]ː?"
local F = "[ɐaeiɵʉE]ː?"
local C = "[mpbwntdsjlrŋkɡxʒʃɕfhɣz]"
local P = "[mpbwntdsjlrŋkɡxʒʃɕfhɣɫz]ʲ?"

local phon = {
	-- consonants
	["м"]="m",	["п"]="p",	["б"]="b",	["в"]="w",	["н"]="n",	["т"]="t",
	["д"]="d",	["ц"]="ts",	["с"]="s",	["й"]="j",	["л"]="l",	["р"]="r",
	["ӈ"]="ŋ",	["к"]="k",	["г"]="ɡ",	["х"]="x",	["ˮ"]="ʔ",	["ʼ"]="ʔ",
	["ж"]="ʒ",	["ч"]="tɕ",	["ш"]="ʃ",	["щ"]="ɕ",	["ф"]="f",	["з"]="z",
	-- vowels
	["а"]="ʌ",	["е"]="e",	["и"]="i",	["о"]="o",	["у"]="u",
	["я"]="ɐ",	["э"]="æ",	["ы"]="ɨ",	["ё"]="ɵ",	["ю"]="ʉ",
	["ь"]="ʲ",	["ъ"]="ъ",
}

local function phonetic(text)
	text = rlower(text)
	text = rsub(text, "э̇", "ɤ")
	text = rsub(text, "ӑ", "аB")
	text = rsub(text, "̆", "B")
	text = rsub(text, "ӣ", "иM")
	text = rsub(text, "ӯ", "уM")
	text = rsub(text, "̄", "M")
	-- general phonology
	text = rsub(text, ".", phon)
	-- vowel length
	text = rsub(text, "([iɨuʉ])̄", "%1ː")
	text = rsub(text, "([iɨuʉ])M", "%1ː")
	text = rsub(text, "ʌB", "ə")
	text = rsub(text, "ɐB", "E")
	text = rsub(text, "ʌM", "ɑ")
	text = rsub(text, "ɐM", "a")
	-- palatalisation
	text = rsub(text, "([ʲʌɐɑaɤeɨioɵuʉəæъEʔ]ː?)(" .. F .. ")", "%1j%2")
	text = rsub(text, "(" .. C .. ")(" .. F .. ")", "%1ʲ%2")
	text = rsub(text, "^(" .. F .. ")", "j%1")
	text = rsub(text, "ъ", "")
	text = rsub(text, "l([^ʲ])", "ɫ%1")
	text = rsub(text, "jʲ", "j")
	text = rsub(text, "E", "ə")
	-- word-final schwa
	text = rsub(text, "(" .. P .. ")$", "%1ə")
	text = rsub(text, "(" .. P .. ")ʔ$", "%1")
	-- /x/
	text = rsub(text, "^x", "h")
	text = rsub(text, "(" .. V .. ")x(" .. V .. ")", "%1ɣ%2")
	text = rsub(text, "[xh]ʲ", "ç")
	-- stress
	text = "ˈ" .. text
	text = rsub(text, "ˈ%-", "-")
	--[[ vowel reduction
	text = rsub(text, "([^ˈ])[ou]", "%1ʊ")
	text = rsub(text, "^[ou]", "ʊ")
	text = rsub(text, "([^ˈ])[ae]", "%1ə")
	text = rsub(text, "^[ae]", "ə")
	]]--
	-- affricates
	text = rsub(text, "ts", "t͡s")
	text = rsub(text, "tɕ", "t͡ɕ")
	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