local export = {}

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

local V = "[aeiou]ː?"
local Vs = "[aeioumnrlwj]ː?"

local phon = {
	-- vowels
	["a"]="a",	["e"]="e",	["i"]="i",	["o"]="o",	["u"]="u",
	["ê"]="εː",	["ô"]="ɔː",
	-- consonants
	["p"]="p",	["b"]="b",	["f"]="f",	["v"]="v",	["m"]="m",
	["t"]="t",	["d"]="d",	["s"]="s",	["n"]="n",	["z"]="dz",
	["k"]="k",	["g"]="ɡ",	["l"]="l",	["r"]="r",	["h"]="h",
}

local function phonetic(text)
	text = rlower(text)
	-- long vowels
	text = rsub(text, "ā", "aM")
	text = rsub(text, "ē", "eM")
	text = rsub(text, "ī", "iM")
	text = rsub(text, "ō", "oM")
	text = rsub(text, "ū", "uM")
	text = rsub(text, "(" .. V .. ")M", "%1ː")
	-- consonant digraphs
	text = rsub(text, "th", "θ")
	text = rsub(text, "ch", "χ")
	-- general phonology
	text = rsub(text, '.', phon)
	text = rsub(text, "([iu])ː", "%1%1")
	text = rsub(text, "(" .. V .. ")i(" .. V .. ")", "%1j%2")
	text = rsub(text, "(" .. V .. ")u(" .. V .. ")", "%1w%2")
	text = rsub(text, "([iu])%1", "%1ː")
	text = rsub(text, "([pbtdkɡfθsχmnlr])%1", "%1ː")
	text = rsub(text, "n([ɡkχ])", "ŋ%1")
	-- intervocalic consonants
	text = rsub(text, "(" .. Vs .. ")ɡ(" .. Vs .. ")", "%1ɣ%2")
	text = rsub(text, "(" .. Vs .. ")θ(" .. Vs .. ")", "%1ð%2")
	text = rsub(text, "(" .. Vs .. ")f(" .. Vs .. ")", "%1v%2")
	text = rsub(text, "(" .. Vs .. ")s(" .. Vs .. ")", "%1z%2")
	-- affricates
	text = rsub(text, "ts", "t͡s")
	text = rsub(text, "dz", "d͡z")
	-- diphthongs
	text = rsub(text, "i([auoe])ː", "j%1ː")
	text = rsub(text, "i([uo])", "j%1")
	text = rsub(text, "e(ː?)i", "e%1i̯")
	text = rsub(text, "a(ː?)u", "a%1u̯")
	
	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_a.format_qualifiers(lang, {"13<sup>th</sup> CE"}) .. " " .. m_IPA.format_IPA_full { lang = lang, items = IPA_results }
end

return export