local export = {}

local codepoint_to_script = require("Module:scripts").charToScript

-- If there are characters in both scripts (the key and value), the value
-- should be used.
local overridden_by = {
	Latn = "Latinx",
	Grek = "polytonic",
	Cyrl = "Cyrs",
}

local function get_script(text)
	local sc, curr_sc
	for codepoint in mw.ustring.gcodepoint(text) do
		curr_sc = codepoint_to_script(codepoint)
		if curr_sc ~= "None" then
			if sc == nil then
				sc = curr_sc
			elseif curr_sc ~= sc then
				-- For instance, Grek -> polytonic.
				if overridden_by[sc] == curr_sc then
					sc = curr_sc
				
				-- For instance, Grek and Latn.
				elseif overridden_by[curr_sc] ~= sc then
					require("Module:debug").track("also/no sc detected")
					mw.log("Two scripts found in " .. tostring(text) .. ": "
						.. tostring(sc) .. " and " .. tostring(curr_sc) .. ".")
					sc = nil
					break
				end
			end
		end
	end
	return sc
end

local function link(text, sc)
	return '<span class="' .. sc .. '">[[' .. text .. ']]</span>'
end

function export.tag_link(link_innards, text)
	local sc = get_script(text or link_innards) or "None"
	
	return link(link_innards, sc)
end

function export.tag_links(str)
	str = str:gsub('%[%[(.-)%]%]', function (innards)
		local sc
		-- The actual displayed text, whose script we need to detect,
		-- if different from link innards.
		local text
		
		if innards:find("|") then
			text = innards:match("|(.+)%]%]$")
			if not text then
				return
			end
		end
		
		return export.tag_link(innards, text)
	end)
	
	return str
end

function export.tag_links_frame(frame)
	local args = {}
	for k, v in pairs(frame:getParent().args) do
		if k == 1 then
			args[k] = v
		else
			error("The parameter " .. k .. " is not used by this template.")
		end
	end
	
	local text = args[1]
	if text then
		text = mw.text.trim(text)
		return export.tag_links(text)
	end
end

function export.link(frame)
	local args = {}
	for k, v in pairs(frame:getParent().args) do
		if k == 1 then
			args[k] = v
		else
			error("The parameter " .. k .. " is not used by this template.")
		end
	end
	
	local text = args[1]
	if text then
		return export.tag_link(text)
	end
end

return export