local p = {}

-- Get a link to the given Wikidata item's page on the first of the following places:
--  1. Wikisource
--  2. Wikipedia
--  3. Commons
--  4. Reasonator
function p.link(frame)
	-- Check input.
	if frame.args.wikidata == nil or frame.args.wikidata == '' then
		return "<span class='error'>Please specify 'wikidata' parameter.</span>"
	end
	local itemId = frame.args.wikidata
	if not mw.wikibase.isValidEntityId(itemId) then
		return "<span class='error'>" .. itemId .. "' is not a valid Wikidata item.</span>"
	end
	if not mw.wikibase.entityExists(itemId) then
		return "<span class='error'>" .. itemId .. "' does not exist on Wikidata.</span>"
	end
	
	local label = mw.wikibase.getLabel(itemId)
	if frame.args.label ~= nil and frame.args.label ~= '' then
		label = frame.args.label
	end

	-- Look through the site hierarchy for a matching sitelink.
	-- These two variables are in the same order.
	local sitelinks =  {'enwikisource', 'enwiki',    'commonswiki'}
	local interwikis = {'',             'wikipedia', 'commons'    }
	for i = 1, #sitelinks do
		local sitelink = mw.wikibase.getSitelink(itemId, sitelinks[i])
		if sitelink then
			return '<span class="module-wikidata-link">[[' .. interwikis[i] .. ':' .. sitelink .. '|' .. label .. ']]</span>';
		end
	end

	-- No interwiki found, so check for a Commons category (P373)
	local P373 = mw.wikibase.getBestStatements(itemId, 'P373')[1]
	if P373 ~= nil and P373 ~= "" then
		local mainsnak = P373["mainsnak"]
		if mainsnak ~= nil and mainsnak ~= "" then
			local datavalue = mainsnak["datavalue"]
			if datavalue ~= nil and datavalue ~= "" then
				local value = datavalue["value"]
				if value ~= nil and value ~= "" then
					return '<span class="module-wikidata-link">[[c:Category:' .. value .. '|' .. label .. ']]</span>';
				end
			end
		end
	end
	
	-- No interwiki or Commons category (P373) found, so check for topic's main category (P910)
	local P910 = mw.wikibase.getBestStatements(itemId, 'P910')[1]
	if P910 ~= nil and P910 ~= "" then
		local mainsnak = P910["mainsnak"]
		if mainsnak ~= nil and mainsnak ~= "" then
			local datavalue = mainsnak["datavalue"]
			if datavalue ~= nil and datavalue ~= "" then
				local value = datavalue["value"]
				if value ~= nil and value ~= "" then
					local id = value["id"]
					if id ~= nil and id ~= "" then
						local sitelink = mw.wikibase.getSitelink(id, 'commonswiki')
						return '<span class="module-wikidata-link">[[c:' .. sitelink .. '|' .. label .. ']]</span>';
					end
				end
			end
		end
	end

	-- Otherwise fall back to Reasonator
	return '<span class="plainlinks module-wikidata-link reasonator-link">[https://reasonator.toolforge.org/?q=' .. itemId .. ' ' .. label .. ']</span>'
end

return p