local export = {}

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

local V = "[aeiouɨɐɪʊ]Q?"
local C = "[bvɣdʒzjklmnprstfxsʃцчɡðθɫcɟđ]ʲ?"

local phon = {
	['а']='a', ['б']='b', ['в']='v', ['г']='ɣ', ['д']='d',
	['е']='ʲe', ['ж']='ʒ', ['з']='z', ['и']='ʲi', ['й']='j', ['к']='k', ['л']='l', 
	['м']='m', ['н']='n', ['о']='o', ['п']='p', ['р']='r', ['с']='s', 
	['т']='t', ['у']='u', ['ф']='f', ['х']='x', ['ц']='ц', ['ч']='ч', ['ш']='ʃ', ['щ']='ɕ',
	['ы']='ɨ', ['э']='e', ['ю']='ʲu', ['я']='ʲa', ['ь']='ʲ', ['́']="Q"
}

local function phonetic(text)
	text = rlower(text)
	-- digraphs
	text = rsub(text, "гк", "ɡ")
	text = rsub(text, "дъ", "ð")
	text = rsub(text, "тъ", "θ")
	text = rsub(text, "дж", "đ")
	-- general phonology
	text = rsub(text, ".", phon)
	-- palatalisation
	text = rsub(text, "(" .. V .. ")ʲ", "%1j")
	text = rsub(text, "^ʲ", "j")
	text = rsub(text, "([ʒʃđ])ʲi", "%1ɨ")
	text = rsub(text, "([ʒʃđ])ʲiQ", "%1ɨQ")
	text = rsub(text, "jʲ", "j")
	text = rsub(text, "чʲ", "ч")
	text=  rsub(text, "ɕʲ", "ɕ")
	text = rsub(text, "kʲ", "c")
	text = rsub(text, "ɡʲ", "ɟ")
	text = rsub(text, "l", "ɫ")
	text = rsub(text, "ɫʲ", "lʲ")
	-- unstressed vowels
	text = rsub(text, "a", "A")
	text = rsub(text, "e", "E")
	text = rsub(text, "i", "I")
	text = rsub(text, "o", "O")
	text = rsub(text, "u", "U")
	text = rsub(text, "ɨ", "Y")
	text = rsub(text, "AQ", "ˈa")
	text = rsub(text, "EQ", "ˈe")
	text = rsub(text, "IQ", "ˈi")
	text = rsub(text, "OQ", "ˈo")
	text = rsub(text, "UQ", "ˈu")
	text = rsub(text, "YQ", "ˈɨ")
	text = rsub(text, "A", "ɐ")
	text = rsub(text, "E", "ɨ")
	text = rsub(text, "I", "ɨ")
	text = rsub(text, "O", "ʊ")
	text = rsub(text, "U", "u")
	text = rsub(text, "Y", "ɨ")
	-- stress
	text = rsub(text, "(" .. C .. ")ˈ", "ˈ%1")
	text = rsub(text, "^(" .. C .. ")ˈ", "ˈ%1")
	-- vowels
	text = rsub(text, "e(ˈ?" .. C .. V .. ")", "ɛ%1")
	text = rsub(text, "e$", "ɛ")
	text = rsub(text, "a", "ä")
	text = rsub(text, "([jчcɟɕ])ä", "a")
	text = rsub(text, "([jʲчcɟɕ])ɨ", "%1ɪ")
	text = rsub(text, "u", "ʊ")
	text = rsub(text, "^(ˈ?)j([iɪ])", "%1(j)%2")
	-- affricates
	text = rsub(text, "ц", "t͡s")
	text = rsub(text, "ч", "t͡ɕ")
	text = rsub(text, "đ", "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