-- This module processes data from [[Module:Signpost/index]], to be loaded from
-- [[Module:Signpost]] with mw.loadData.

local PAGE_FORMAT = 'Wikipedia:Wikipedia Signpost/%s/%s'
local INDEX_START_YEAR = 2005
local INDEX_BASE = 'Module:Signpost/index/'
local ALIASES_MODULE = 'Module:Signpost/aliases'
local insert = table.insert
local format = string.format

local function makePageName(date, subpage)
	return format(PAGE_FORMAT, date, subpage)
end

local function addSubtable(tIn, tOut, key)
	tOut[key] = tOut[key] or {}
	insert(tOut[key], tIn)
end

local function maybeRequire(page)
	local success, module = pcall(require, page)
	if success then
		return module
	end
end

local function getYearIndexes()
	local ret = {}
	for i = INDEX_START_YEAR, os.date('*t').year + 1 do
		local module = maybeRequire(INDEX_BASE .. tostring(i))
		insert(ret, module)
	end
	return ret
end

local function makeAliases()
	local aliasData = require(ALIASES_MODULE)
	local ret = {}
	for key, aliases in pairs(aliasData) do
		for i, alias in ipairs(aliases) do
			ret[alias] = key
		end
	end
	return ret
end

local function addArticleToIndex(index, article, sortKey)
	article.sortKey = sortKey
	index.list[sortKey] = article

	local date = article.date
	addSubtable(article, index.dates, date)

	local page = makePageName(date, article.subpage)
	article.page = page
	index.pages[page] = article

	article.tags = article.tags or {}
	for l, tag in ipairs(article.tags) do
		addSubtable(article, index.tags, tag)
	end

	article.authors = article.authors or {}
	for l, author in ipairs(article.authors) do
		addSubtable(article, index.authors, author)
	end
end

local function main()
	local index = {
		aliases = makeAliases(),
		authors = {},
		dates = {},
		list = {},
		pages = {},
		tags = {},
	}
	local sortKey = 0
	for j, yearIndex in ipairs(getYearIndexes()) do
		for k, article in ipairs(yearIndex) do
			sortKey = sortKey + 1
			addArticleToIndex(index, article, sortKey)
		end
	end
	return index
end

return main()