Module:Madlibs

From Uncyclopedia, the content-free encyclopedia
Jump to navigation Jump to search

local p = {}

-- Cache for loaded data modules
local moduleCache = {}

local DATA_ROOT = "Module:Madlibs/data/"

-- Load alias configuration
local function loadAliases()
    local ok, config = pcall(require, "Module:Madlibs/config")
    return (ok and type(config) == "table" and config.aliases) or {}
end
local aliases = loadAliases()

-- Normalize input (trim + lowercase)
local function normalizeKey(s)
    s = mw.text.trim(s or "")
    return s ~= "" and mw.ustring.lower(s) or nil
end

-- Resolve alias → actual module name
local function resolveKey(key)
    key = normalizeKey(key)
    if not key then return nil end

    for moduleName, aliasList in pairs(aliases) do
        for _, alias in ipairs(aliasList) do
            if normalizeKey(alias) == key then
                return moduleName
            end
        end
    end

    -- fallback: assume user typed the real module name
    return key
end

-- Load a data list from Module:Madlibs/data/<key>
local function loadList(key)
    key = resolveKey(key)
    if not key then return nil, "Data page not found or invalid alias" end

    if moduleCache[key] then return moduleCache[key] end

    local moduleName = DATA_ROOT .. key
    local ok, data = pcall(require, moduleName)
    if not ok or type(data) ~= "table" then
        return nil, "Data page does not exist or is not a subpage of <code>Module:Madlibs/data</code> " ..
                    "(expected <code>" .. moduleName .. "</code>)"
    end
    if #data == 0 then
        return nil, "Data page <code>" .. moduleName .. "</code> is empty (must return a non-empty list)"
    end

    moduleCache[key] = data
    return data
end

-- Main entry point
function p.main(frame)
    local key = frame.args[1]
    if not key then return '<span class="error">Error: No data name specified</span>' end

    math.randomseed(os.time() + (tonumber(frame.args[2]) or 0))

    local list, err = loadList(key)
    if not list then return '<span class="error">Error: ' .. err .. '</span>' end

    return list[math.random(#list)]
end

return p