local p = {}

---
-- Check if a page exists
--
-- @param  {string} title Page title
-- @return {boolean}
function pageExists( title )
	local page = mw.title.new( title )
	return page and page.exists
end

---
-- Return a wikilink (also a red link)
--
-- Example: [[Universe]] from "Q1"
--
-- Note that the link can be a red link.
-- The label will be used as title in that case.
--
-- In the rare case that the page already exists but it's not a sitelink,
-- the 'disambiguation' parameter can be used to create a link like:
--   "[[Wikidata Label Here (Disambiguation Text)]]"
--
-- @param  {string} entity         Entity Q-ID
-- @param  {string} disambiguation Optional disambiguation text
-- @return {string}                Wikilink to the entity ID
function p._main( entity, disambiguation )
	if not entity then return end

	-- the default URL is just the entity Q-id, for further troubleshooting
	local link = entity

	-- get the sitelink of this entity
	local siteLink = mw.wikibase.getSitelink( entity )

	-- get the label of this entity
	local label = mw.wikibase.getLabel( entity )

	if siteLink then
		-- prepare an internal wikilink to an existing page
		link = string.format( '[[%s]]', siteLink )
	else
		if label then
			-- if the page already exists, try a disambiguation
			if disambiguation and pageExists( label ) then
			
				-- prepare a red link to an unexisting disambiguated page
				link = string.format( '[[%s (%s)]]', label, disambiguation )
			else

				-- prepare a red link to an unexisting page
				link = string.format( '[[%s]]', label )
			end
		end	
	end

	-- return the wikilink
	return link
end

---
-- Return a wikilink (also a red link)
--
-- Example: [[Universe]] from "Q1"
--
-- Note that the link can be a red link.
-- The label will be used as title in that case.
--
-- @param  {object} frame
-- @return {string} Wikilink to the entity ID
function p.main( frame )

	-- module to handle arguments
	local getArgs = require( 'Module:Arguments' ).getArgs

	-- arguments passed to the module (or from the template)
	local args = getArgs( frame )

	-- the entity can be the arg 'id' or the 1st argument
	-- anyway it's optional and the current page will be used if nil
	local entity = args.id or args[1]
	
	-- the page can be the arg 'disamb' or the 2st argument
	local disambiguation = args.disamb or args[2]

	-- see the p.main() function reference
	return p._main( entity, disambiguation )
end

return p