Module:DidYouKnow

From Piñata Journal

Documentation for this module may be created at Module:DidYouKnow/doc

local p = {}

-- CONFIG
local DATA_PAGE = "Template:Did you know/Data"
local DEFAULT_COUNT = 5
local MAX_COUNT = 15

-- Simple deterministic shuffle
local function shuffle(t)
    for i = #t, 2, -1 do
        local j = math.random(i)
        t[i], t[j] = t[j], t[i]
    end
end

function p.main(frame)
    local args = frame.args
    local count = tonumber(args.count) or DEFAULT_COUNT
    if count > MAX_COUNT then
        count = MAX_COUNT
    end

    local title = mw.title.new(DATA_PAGE)
    if not title or not title.exists then
        return "<span class='error'>DidYouKnow: data page not found</span>"
    end

    local content = title:getContent()
    if not content then
        return "<span class='error'>DidYouKnow: no content</span>"
    end

    local items = {}

    -- Parse bullet list
    for line in content:gmatch("[^\r\n]+") do
        local item = line:match("^%*%s*(.+)")
        if item then
            table.insert(items, item)
        end
    end

    if #items == 0 then
        return "<span class='error'>DidYouKnow: no items found</span>"
    end

    -- Daily seed (YYYYMMDD)
    local today = os.date("%Y%m%d")
    math.randomseed(tonumber(today))
    math.random() -- discard first value

    -- Shuffle and select
    shuffle(items)

    if count > #items then
        count = #items
    end

    -- Build output list
    local out = {}
    table.insert(out, "<ul class='did-you-know-list'>")

    for i = 1, count do
        table.insert(out, "<li>" .. items[i] .. "</li>")
    end

    table.insert(out, "</ul>")

    return table.concat(out, "\n")
end

return p