Jump to content

Module:AchievementSystem: Difference between revisions

// via Wikitext Extension for VSCode
// via Wikitext Extension for VSCode
 
(30 intermediate revisions by the same user not shown)
Line 1: Line 1:
-- Module:AchievementSystem
--[[
-- Achievement system that loads data from MediaWiki:AchievementData.json.
* Name: AchievementSystem
-- STYLING NOTE: All achievement styling is defined in CSS/Templates.css, not in the JSON.
* Author: Mark W. Datysgeld
-- This module only assigns CSS classes based on achievement IDs in the format:
* Description: Comprehensive achievement system that manages user badges and titles throughout ICANNWiki, loading data from MediaWiki JSON files and providing rendering functions for Person templates
--   .person-template .template-title.achievement-{id}::after {}
* Notes: Loads from MediaWiki:AchievementData.json (user assignments) and MediaWiki:AchievementList.json (type definitions). CSS styling defined in Templates.css using achievement-{id} format. Includes caching and fallback mechanisms for robust JSON handling
--
]]
-- The module does not use any styling information from the JSON data structure.
 
---@class UserAchievement
---@field type string
---@field date? string


local Achievements = {}
local Achievements = {}
-- Debug configuration
local DEBUG_MODE = true
local function debugLog(message)
    if not DEBUG_MODE then return end
    pcall(function()
        mw.logObject({
            system = "achievement_simple",
            message = message,
            timestamp = os.date('%H:%M:%S')
        })
    end)
    mw.log("ACHIEVEMENT-DEBUG: " .. message)
end


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- JSON Handling
-- JSON Handling
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- We'll use MediaWiki's built-in JSON functions directly, no external module needed
-- Helper function to ensure we get an array
local function ensureArray(value)
    if type(value) ~= "table" then
        return {}
    end
   
    -- Check if it's an array-like table
    local isArray = true
    local count = 0
    for _ in pairs(value) do
        count = count + 1
    end
   
    -- If it has no numeric indices or is empty, return empty array
    if count == 0 then
        return {}
    end
   
    -- If it's a single string, wrap it in an array
    if count == 1 and type(value[1]) == "string" then
        return {value[1]}
    end
   
    -- If it has a single non-array value, try to convert it to an array
    if count == 1 and next(value) and type(next(value)) ~= "number" then
        local k, v = next(value)
        if type(v) == "string" then
            return {v}
        end
    end
   
    -- Return the original table if it seems to be an array
    return value
end
 
-- Use MediaWiki's built-in JSON functions directly
local function jsonDecode(jsonString)
local function jsonDecode(jsonString)
     if not jsonString then  
     if not jsonString then return nil end
        debugLog('ERROR: Empty JSON string provided')
        return nil  
    end
      
      
     if mw.text and mw.text.jsonDecode then
     if mw.text and mw.text.jsonDecode then
         local success, result = pcall(function()
         local success, result = pcall(function()
            -- Use WITHOUT PRESERVE_KEYS flag to ensure proper array handling
             return mw.text.jsonDecode(jsonString)
             return mw.text.jsonDecode(jsonString)
         end)
         end)
          
          
         if success and result then
         if success and result then
             -- Validate the structure has achievement_types array
             return result
            if type(result) == 'table' and result.achievement_types then
                debugLog('SUCCESS: JSON decode successful with ' .. #result.achievement_types .. ' achievement types')
                return result
            else
                debugLog('ERROR: JSON decode succeeded but missing achievement_types array or not a table')
                if type(result) == 'table' then
                    for k, _ in pairs(result) do
                        debugLog('Found key in result: ' .. k)
                    end
                end
            end
        else
            debugLog('ERROR: JSON decode failed: ' .. tostring(result or 'unknown error'))
         end
         end
     end
     end
      
      
    debugLog('CRITICAL ERROR: mw.text.jsonDecode not available!')
     return nil
     return nil
end
end
Line 76: Line 84:
-- Configuration, Default Data, and Cache
-- Configuration, Default Data, and Cache
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local ACHIEVEMENT_DATA_PAGE = 'MediaWiki:AchievementData.json'
local ACHIEVEMENT_DATA_PAGE = 'MediaWiki:AchievementData.json'
local ACHIEVEMENT_LIST_PAGE = 'MediaWiki:AchievementList.json'
local dataCache = nil
local dataCache = nil
local typesCache = nil


local DEFAULT_DATA = {
local DEFAULT_DATA = {
     schema_version = 1,
     schema_version = 2,
     last_updated = os.date('!%Y-%m-%dT%H:%M:%SZ'),
     last_updated = os.date('!%Y-%m-%dT%H:%M:%SZ'),
     achievement_types = {},
     achievement_types = {},
     user_achievements = {},
     user_achievements = {},
    cache_control = { version = 0 }
}
}


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Configuration
-- Load achievement types from the JSON page
-- @param frame - The Scribunto frame object for preprocessing
-- @return Array of achievement type definitions
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- This array maps legacy achievement IDs to standardized ones
function Achievements.loadTypes(frame)
local ACHIEVEMENT_TYPE_MAPPING = {
    -- Use the request-level cache if we already loaded data once
    ["title-test"] = "dev-role",
    if typesCache then
    ["jedi"]      = "ach1",
        return typesCache
    ["champion"= "ach2",
    end
    ["sponsor"]  = "ach3"
 
}
    local success, types = pcall(function()
        -- Get the JSON content using frame:preprocess if available
        local jsonText
        if frame and type(frame) == "table" and frame.preprocess then
            -- Make sure frame is valid and has preprocess method
            local preprocessSuccess, preprocessResult = pcall(function()
                return frame:preprocess('{{MediaWiki:AchievementList.json}}')
            end)
           
            if preprocessSuccess and preprocessResult then
                jsonText = preprocessResult
            end
        end
       
        -- If we couldn't get JSON from frame:preprocess, fall back to direct content loading
        if not jsonText then
            -- Try using mw.loadJsonData first (preferred method)
            if mw.loadJsonData then
                local loadJsonSuccess, jsonData = pcall(function()
                    return mw.loadJsonData(ACHIEVEMENT_LIST_PAGE)
                end)
               
                if loadJsonSuccess and jsonData and type(jsonData) == 'table' and jsonData.achievement_types then
                    return jsonData.achievement_types
                end
            end
           
            -- Direct content loading approach as fallback
            local pageTitle = mw.title.new(ACHIEVEMENT_LIST_PAGE)
            if pageTitle and pageTitle.exists then
                -- Get raw content from the wiki page
                local contentSuccess, content = pcall(function()
                    return pageTitle:getContent()
                end)
               
                if contentSuccess and content and content ~= "" then
                    -- Remove any BOM or leading whitespace that might cause issues
                    content = content:gsub("^%s+", "")
                    if content:byte(1) == 239 and content:byte(2) == 187 and content:byte(3) == 191 then
                        content = content:sub(4)
                    end
                   
                    jsonText = content
                   
                    -- Try different JSON decode approaches
                    if jsonText and mw.text and mw.text.jsonDecode then
                        -- First try WITHOUT PRESERVE_KEYS flag (standard approach)
                        local jsonDecodeSuccess, jsonData = pcall(function()
                            return mw.text.jsonDecode(jsonText)
                        end)
                       
                        if jsonDecodeSuccess and jsonData and jsonData.achievement_types then
                            return jsonData.achievement_types
                        end
                       
                        -- If that failed, try with JSON_TRY_FIXING flag
                        jsonDecodeSuccess, jsonData = pcall(function()
                            return mw.text.jsonDecode(jsonText, mw.text.JSON_TRY_FIXING)
                        end)
                       
                        if jsonDecodeSuccess and jsonData and jsonData.achievement_types then
                            return jsonData.achievement_types
                        end
                    end
                end
            end
           
            -- If we couldn't load from AchievementList.json, fall back to AchievementData.json
            local data = Achievements.loadData(frame)
            if data and data.achievement_types then
                return data.achievement_types
            end
        else
            -- We have jsonText from frame:preprocess, try to decode it
            if jsonText and mw.text and mw.text.jsonDecode then
                -- First try WITHOUT PRESERVE_KEYS flag (standard approach)
                local jsonDecodeSuccess, jsonData = pcall(function()
                    return mw.text.jsonDecode(jsonText)
                end)
               
                if jsonDecodeSuccess and jsonData and jsonData.achievement_types then
                    return jsonData.achievement_types
                end
               
                -- If that failed, try with JSON_TRY_FIXING flag
                jsonDecodeSuccess, jsonData = pcall(function()
                    return mw.text.jsonDecode(jsonText, mw.text.JSON_TRY_FIXING)
                end)
               
                if jsonDecodeSuccess and jsonData and jsonData.achievement_types then
                    return jsonData.achievement_types
                end
            end
           
            -- If we couldn't decode the JSON, fall back to AchievementData.json
            local data = Achievements.loadData(frame)
            if data and data.achievement_types then
                return data.achievement_types
            end
        end
       
        -- As an absolute last resort, return an empty array
        return {}
    end)


-- Normalizes achievement type to handle variants or legacy types
    if not success or not types then
local function normalizeAchievementType(achievementType)
        -- If there was an error, fall back to AchievementData.json
    if not achievementType then  
        local data = Achievements.loadData(frame)
         debugLog("Normalize called with nil achievement type")
        if data and data.achievement_types then
         return nil
            typesCache = data.achievement_types
            return typesCache
         end
         types = {}
     end
     end
   
 
    -- Always log the normalization attempt for debugging
     typesCache = types
    debugLog("Normalizing achievement type: '" .. tostring(achievementType) .. "'")
     return types
   
    -- If it's already a standard type, return it directly
     if achievementType == "dev-role" or
      achievementType == "ach1" or
      achievementType == "ach2" or
      achievementType == "ach3" or
      achievementType == "sponsor-role" then
        debugLog("Achievement type already standardized: " .. achievementType)
        return achievementType
    end
   
    -- Otherwise check the mapping table
    local mappedType = ACHIEVEMENT_TYPE_MAPPING[achievementType] or achievementType
   
    if mappedType ~= achievementType then
        debugLog("Mapped legacy achievement type '" .. achievementType .. "' to '" .. mappedType .. "'")
    end
   
     return mappedType
end
end


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Load achievement data from the JSON page
-- Load achievement data from the JSON page
-- @param frame - The Scribunto frame object for preprocessing
-- @return Table containing the full achievement data
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.loadData()
function Achievements.loadData(frame)
    mw.log("JSON-DEBUG: Starting to load achievement data")
 
     -- Use the request-level cache if we already loaded data once
     -- Use the request-level cache if we already loaded data once
     if dataCache then
     if dataCache then
        mw.log("JSON-DEBUG: Using request-level cached data")
         return dataCache
         return dataCache
     end
     end


     local data = DEFAULT_DATA
     local success, data = pcall(function()
    local jsonLoadingMethod = "none"
        -- Get the JSON content using frame:preprocess if available
   
        local jsonText
    -- SIMPLIFIED LOADING APPROACH - prioritizing mw.text.jsonDecode as it correctly processes achievement types
        if frame and type(frame) == "table" and frame.preprocess then
    mw.log("JSON-DEBUG: === SIMPLIFIED JSON LOADING START ===")
            -- Make sure frame is valid and has preprocess method
   
            local preprocessSuccess, preprocessResult = pcall(function()
    -- First get the title and check if page exists
                return frame:preprocess('{{MediaWiki:AchievementData.json}}')
    local pageTitle = mw.title.new(ACHIEVEMENT_DATA_PAGE)
            end)
    if not pageTitle or not pageTitle.exists then
           
        mw.log("JSON-DEBUG: " .. ACHIEVEMENT_DATA_PAGE .. " does not exist or title creation failed")
            if preprocessSuccess and preprocessResult then
        return DEFAULT_DATA
                jsonText = preprocessResult
    end
            end
   
         end
    mw.log("JSON-DEBUG: Page exists with content model: " .. tostring(pageTitle.contentModel))
   
    -- First attempt: Use direct raw content with mw.text.jsonDecode
    -- Based on diagnostic output, this is the most reliable method
    if mw.text and mw.text.jsonDecode then
        local content = nil
        local contentSuccess, contentResult = pcall(function()
            return pageTitle:getContent()
         end)
          
          
         if contentSuccess and contentResult and contentResult ~= "" then
        -- If we couldn't get JSON from frame:preprocess, fall back to direct content loading
             content = contentResult
         if not jsonText then
             mw.log("JSON-DEBUG: Successfully retrieved raw content, length: " .. #content)
             -- Try using mw.loadJsonData first (preferred method)
             if mw.loadJsonData then
                local loadJsonSuccess, jsonData = pcall(function()
                    return mw.loadJsonData(ACHIEVEMENT_DATA_PAGE)
                end)
               
                if loadJsonSuccess and jsonData and type(jsonData) == 'table' then
                    return jsonData
                end
            end
              
              
             -- Remove any BOM or leading whitespace that might cause issues
             -- Direct content loading approach as fallback
             content = content:gsub("^%s+", "")
             local pageTitle = mw.title.new(ACHIEVEMENT_DATA_PAGE)
             if content:byte(1) == 239 and content:byte(2) == 187 and content:byte(3) == 191 then
             if not pageTitle or not pageTitle.exists then
                 mw.log("JSON-DEBUG: Removing UTF-8 BOM from content")
                 return DEFAULT_DATA
                content = content:sub(4)
             end
             end
              
              
             local jsonDecodeSuccess, jsonData = pcall(function()
            -- Get raw content from the wiki page
                 return mw.text.jsonDecode(content)
             local contentSuccess, content = pcall(function()
                 return pageTitle:getContent()
             end)
             end)
              
              
             if jsonDecodeSuccess and jsonData and type(jsonData) == 'table' then
             if contentSuccess and content and content ~= "" then
                 -- Validate the structure
                 -- Remove any BOM or leading whitespace that might cause issues
                 if jsonData.achievement_types and #jsonData.achievement_types > 0 and jsonData.user_achievements then
                 content = content:gsub("^%s+", "")
                    mw.log("JSON-DEBUG: ✓ Successfully decoded with mw.text.jsonDecode, found " ..
                if content:byte(1) == 239 and content:byte(2) == 187 and content:byte(3) == 191 then
                          #jsonData.achievement_types .. " achievement types")
                     content = content:sub(4)
                   
                    -- Log achievement types
                    for i, typeData in ipairs(jsonData.achievement_types) do
                        mw.log("JSON-DEBUG: Type[" .. i .. "]: id=" .. (typeData.id or "nil") ..
                              ", name=" .. (typeData.name or "nil") ..
                              ", type=" .. (typeData.type or "nil"))
                    end
                   
                    data = jsonData
                     jsonLoadingMethod = "mw.text.jsonDecode"
                else
                    mw.log("JSON-DEBUG: ✗ mw.text.jsonDecode result missing required fields or empty achievement_types")
                    if jsonData.achievement_types then
                        mw.log("JSON-DEBUG: Found achievement_types but it contains " ..
                              #jsonData.achievement_types .. " items")
                    end
                 end
                 end
               
                jsonText = content
             else
             else
                 mw.log("JSON-DEBUG: ✗ mw.text.jsonDecode failed: " ..
                 return DEFAULT_DATA
                      tostring(jsonData or 'unknown error'))
             end
             end
        else
            mw.log("JSON-DEBUG: ✗ Failed to get raw content: " ..
                  tostring(contentResult or 'unknown error'))
         end
         end
    else
        mw.log("JSON-DEBUG: ✗ mw.text.jsonDecode not available")
    end
   
    -- Second attempt: Only if first attempt failed, try mw.loadJsonData
    if jsonLoadingMethod == "none" and mw.loadJsonData then
        mw.log("JSON-DEBUG: Attempting mw.loadJsonData as fallback")
          
          
         local loadJsonSuccess, jsonData = pcall(function()
         -- Try different JSON decode approaches
            return mw.loadJsonData(ACHIEVEMENT_DATA_PAGE)
        if jsonText and mw.text and mw.text.jsonDecode then
        end)
            -- First try WITHOUT PRESERVE_KEYS flag (standard approach)
       
            local jsonDecodeSuccess, jsonData = pcall(function()
        if loadJsonSuccess and jsonData and type(jsonData) == 'table' then
                return mw.text.jsonDecode(jsonText)
             -- Validate the structure
            end)
             if jsonData.achievement_types and #jsonData.achievement_types > 0 and jsonData.user_achievements then
           
                mw.log("JSON-DEBUG: ✓ Successfully loaded with mw.loadJsonData, found " ..
            if jsonDecodeSuccess and jsonData then
                      #jsonData.achievement_types .. " achievement types")
                return jsonData
                  
             end
                data = jsonData
              
                jsonLoadingMethod = "mw.loadJsonData"
            -- If that failed, try with JSON_TRY_FIXING flag
            else
            jsonDecodeSuccess, jsonData = pcall(function()
                mw.log("JSON-DEBUG: ✗ mw.loadJsonData result missing required fields or empty achievement_types")
                 return mw.text.jsonDecode(jsonText, mw.text.JSON_TRY_FIXING)
                if jsonData.achievement_types then
            end)
                    mw.log("JSON-DEBUG: Found achievement_types but it contains " ..
           
                          #jsonData.achievement_types .. " items")
            if jsonDecodeSuccess and jsonData then
                   
                return jsonData
                    -- This is likely the issue identified in diagnostics - achievement_types exists but is empty
                    -- We'll use the data anyway and log the issue
                    if jsonData.user_achievements then
                        mw.log("JSON-DEBUG: Using partial data from mw.loadJsonData despite empty achievement_types")
                        data = jsonData
                        jsonLoadingMethod = "mw.loadJsonData (partial)"
                    end
                end
             end
             end
        else
            mw.log("JSON-DEBUG: ✗ mw.loadJsonData failed: " ..
                  tostring(jsonData or 'unknown error'))
         end
         end
        -- As an absolute last resort, use local default data
        return DEFAULT_DATA
    end)
    if not success or not data then
        data = DEFAULT_DATA
    end
    dataCache = data
    return data
end
--------------------------------------------------------------------------------
-- Get user achievements
-- @param pageId - The page ID to get achievements for
-- @return Array of achievement objects for the specified page
--------------------------------------------------------------------------------
local userAchievementsCache = {}
---@return UserAchievement[]
function Achievements.getUserAchievements(pageId)
    if not pageId or pageId == '' then
        return {}
     end
     end
      
      
     -- Log which method we used and validation
     -- Check cache first
     mw.log("JSON-DEBUG: JSON loading complete using method: " .. jsonLoadingMethod)
    local cacheKey = tostring(pageId)
     if data ~= DEFAULT_DATA then
    if userAchievementsCache[cacheKey] then
         local achievementTypeCount = data.achievement_types and #data.achievement_types or 0
        return userAchievementsCache[cacheKey]
         local userCount = 0
    end
         if data.user_achievements then
 
             for _, _ in pairs(data.user_achievements) do
     local data = Achievements.loadData()
                userCount = userCount + 1
     if not data or not data.user_achievements then
             end
         return {}
    end
 
    local key = cacheKey
    local userEntry = data.user_achievements[key]
   
    -- If found with string key, return achievements
    if userEntry and userEntry.achievements then
         local achievements = ensureArray(userEntry.achievements)
        userAchievementsCache[cacheKey] = achievements
         return achievements
    end
   
    -- Try numeric key as fallback
    local numKey = tonumber(key)
    if numKey then
        userEntry = data.user_achievements[numKey]
        if userEntry and userEntry.achievements then
             local achievements = ensureArray(userEntry.achievements)
            userAchievementsCache[cacheKey] = achievements
             return achievements
         end
         end
       
        mw.log("JSON-DEBUG: Loaded data with " .. achievementTypeCount ..
              " achievement types and " .. userCount .. " users")
       
        -- Validate achievement types have required fields
        if data.achievement_types then
            for i, typeData in ipairs(data.achievement_types) do
                if not typeData.id or not typeData.name or not typeData.type then
                    mw.log("JSON-DEBUG: WARNING: Achievement type " .. i ..
                          " missing required fields (id, name, or type)")
                end
            end
        end
    else
        mw.log("JSON-DEBUG: WARNING: Using default data due to loading failures")
     end
     end
      
      
     mw.log("JSON-DEBUG: === SIMPLIFIED JSON LOADING END ===")
     -- Cache empty result to avoid repeated lookups
   
     userAchievementsCache[cacheKey] = {}
     dataCache = data
     return {}
     return data
end
end


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Check if a page/user has any achievements
-- Check if a page/user has any achievements
-- @param pageId - The page ID to check
-- @return Boolean indicating if the page has any achievements
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.hasAchievements(pageId)
function Achievements.hasAchievements(pageId)
Line 291: Line 380:
     end
     end


     local data = Achievements.loadData()
     local userAchievements = Achievements.getUserAchievements(pageId)
     if not data or not data.user_achievements then
    return #userAchievements > 0
         return false
end
 
--------------------------------------------------------------------------------
-- Get all badge-type achievements for a user
-- @param pageId - The page ID to check
-- @param frame - The Scribunto frame object for preprocessing
-- @return Array of badge achievement objects
--------------------------------------------------------------------------------
function Achievements.getBadgeAchievements(pageId, frame)
     if not pageId or pageId == '' then
         return {}
     end
     end


     local key = tostring(pageId)
     local userAchievements = Achievements.getUserAchievements(pageId)
     if data.user_achievements[key] and #data.user_achievements[key] > 0 then
     if #userAchievements == 0 then
         return true
         return {}
     end
     end


     -- Check for legacy "n123" style
    local types = Achievements.loadTypes(frame)
     if key:match("^%d+$") then
   
         local alt = "n" .. key
     -- Build a lookup table for achievement types for efficient access
         if data.user_achievements[alt] and #data.user_achievements[alt] > 0 then
    local typeDefinitions = {}
             return true
     for _, typeData in ipairs(types) do
        if typeData.id and typeData.type then
            typeDefinitions[typeData.id] = typeData
        end
    end
   
    local badgeAchievements = {}
    -- Filter user achievements to only include badge types
    for _, achievementTbl in ipairs(userAchievements) do
         local achType = achievementTbl['type']
         if achType and typeDefinitions[achType] and typeDefinitions[achType]['type'] == "badge" then
                local newAchievement = {
                    type = achType,
                    date = achievementTbl['date'] or '',
                    name = typeDefinitions[achType].name or achType,
                    category = typeDefinitions[achType].category
                }
             table.insert(badgeAchievements, newAchievement)
         end
         end
     end
     end


    -- We removed the forced "true" for test pages to avoid dev-role injection
     return badgeAchievements
     return false
end
end


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Get a user-friendly name for a given achievement type
-- Get a user-friendly name for a given achievement type
-- @param achievementType - The achievement type ID
-- @param frame - The Scribunto frame object for preprocessing
-- @return String containing the user-friendly name
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.getAchievementName(achievementType)
function Achievements.getAchievementName(achievementType, frame)
     if not achievementType or achievementType == '' then
     if not achievementType or achievementType == '' then
        debugLog("Empty achievement type provided to getAchievementName")
        mw.log("ACHIEVEMENT-NAME-ERROR: Received empty achievementType")
         return 'Unknown'
         return 'Unknown'
     end
     end


    debugLog("Looking up achievement name for type: '" .. tostring(achievementType) .. "'")
     local types = Achievements.loadTypes(frame)
 
     local data = Achievements.loadData()
    if not data or not data.achievement_types then
        mw.log("ACHIEVEMENT-NAME-ERROR: No achievement data or achievement_types missing")
        return achievementType
    end
   
    -- Log achievement type count to help diagnose issues
    debugLog("Found " .. #data.achievement_types .. " achievement types in data")
      
      
     -- Try to match achievement ID
     -- Try to match achievement ID
     for i, typeData in ipairs(data.achievement_types) do
     for _, typeData in ipairs(types) do
         if typeData.id == achievementType then
         if typeData.id == achievementType then
            debugLog("Found match for " .. achievementType .. " at index " .. i)
           
             if typeData.name and typeData.name ~= "" then
             if typeData.name and typeData.name ~= "" then
                debugLog("Using name '" .. typeData.name .. "' for type '" .. achievementType .. "'")
                 return typeData.name
                 return typeData.name
             else
             else
                debugLog("Type " .. achievementType .. " has no name; using ID as fallback")
                 return achievementType
                 return achievementType
             end
             end
Line 349: Line 452:
     end
     end


    -- If we reach here, no match was found - log all achievement types to help diagnose
    debugLog("No match found for '" .. achievementType .. "' - logging all available types")
    for i, typeData in ipairs(data.achievement_types) do
        debugLog("Available type[" .. i .. "]: id=" .. (typeData.id or "nil") ..
              ", name=" .. (typeData.name or "nil") ..
              ", type=" .. (typeData.type or "nil"))
    end
    debugLog("No achievement found with type '" .. achievementType .. "'; using ID fallback")
     return achievementType
     return achievementType
end
end


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Find the top-tier achievement for the user (lowest tier number)
-- Find the top-tier Title achievement for the user (lowest tier number)
-- Return the CSS class and the readable achievement name
-- Return the CSS class and the readable achievement name
-- @param pageId - The page ID to get the title achievement for
-- @param frame - The Scribunto frame object for preprocessing
-- @return CSS class, display name
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.getTitleClass(pageId)
function Achievements.getTitleClass(pageId, frame)
     if not pageId or pageId == '' then
     if not pageId or pageId == '' then
        debugLog("Empty page ID provided to getTitleClass")
         return '', ''
         return '', ''
     end
     end


     local data = Achievements.loadData()
     local userAchievements = Achievements.getUserAchievements(pageId)
    if not data or not data.user_achievements then
     if #userAchievements == 0 then
        debugLog("No achievement data available in getTitleClass")
        return '', ''
    end
 
    local key = tostring(pageId)
    debugLog("Looking up achievements for page ID: " .. key)
   
    -- Try to fetch achievements for this pageId
    local userAchievements = {}
    local userAchievementKey = key
   
    -- Try the direct key first
     if data.user_achievements[key] and #data.user_achievements[key] > 0 then
        debugLog("Found achievements directly under key: " .. key)
        userAchievements = data.user_achievements[key]
        userAchievementKey = key
    -- If no achievements found under normal ID, try alternative formats
    elseif key:match("^%d+$") then
        local alternateKeys = {
            "n" .. key,      -- n12345 format
            "page" .. key,    -- page12345 format
            "user" .. key    -- user12345 format
        }
       
        for _, altKey in ipairs(alternateKeys) do
            if data.user_achievements[altKey] and #data.user_achievements[altKey] > 0 then
                debugLog("Found achievements under alternate key: " .. altKey)
                userAchievements = data.user_achievements[altKey]
                userAchievementKey = altKey
                break
            end
        end
    end
 
    -- Log achievement count and details
    if #userAchievements > 0 then
        debugLog("Found " .. #userAchievements .. " achievements for page ID " .. key .. " under key " .. userAchievementKey)
        for i, ach in ipairs(userAchievements) do
            debugLog("  Achievement " .. i .. ": type=" .. (ach.type or "nil"))
        end
    else
        debugLog("No achievements found for page ID " .. key .. " under any key")
         return '', ''
         return '', ''
     end
     end


     -- Find the highest-tier achievement (lowest tier number)
     local types = Achievements.loadTypes(frame)
     local highestTier = 999
     local highestTier = 999
     local highestAchievement = nil
     local highestAchievement = nil


     for _, achievement in ipairs(userAchievements) do
     for _, achievement in ipairs(userAchievements) do
         local achType = achievement.type
         local achType = achievement["type"]
        if not achType then
          
            debugLog("Achievement missing type property - skipping")
        for _, typeData in ipairs(types) do
         else
            if typeData.id == achType then
            debugLog("Processing achievement type: " .. achType)
                 local tier = typeData.tier or 999
           
            -- Find the achievement definition for this type
            local achDef = nil
            for _, typeData in ipairs(data.achievement_types) do
                if typeData.id == achType then
                    achDef = typeData
                    break
                end
            end
           
            if not achDef then
                debugLog("No definition found for achievement type: " .. achType)
            else
                 local tier = achDef.tier or 999
                debugLog("  Found type '" .. achDef.id .. "' with tier " .. tier ..
                      ", name '" .. (achDef.name or "nil") ..
                      "', type '" .. (achDef.type or "nil") .. "'")
               
                 if tier < highestTier then
                 if tier < highestTier then
                     highestTier = tier
                     highestTier = tier
                     highestAchievement = achDef
                     highestAchievement = typeData
                    debugLog("  New highest tier achievement: " .. achDef.id)
                 end
                 end
             end
             end
Line 456: Line 491:


     if not highestAchievement or not highestAchievement.id then
     if not highestAchievement or not highestAchievement.id then
        debugLog("No valid top-tier achievement found for page ID " .. key)
         return '', ''
         return '', ''
     end
     end
Line 462: Line 496:
     local cssClass = "achievement-" .. highestAchievement.id
     local cssClass = "achievement-" .. highestAchievement.id
     local displayName = highestAchievement.name or highestAchievement.id or "Award"
     local displayName = highestAchievement.name or highestAchievement.id or "Award"
   
    debugLog("Using top-tier achievement: " .. cssClass .. " with name: " .. displayName)
      
      
     return cssClass, displayName
     return cssClass, displayName
Line 469: Line 501:


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Renders a simple "box" with the top-tier achievement for the user
-- Renders a box with the top-tier achievement for the user
-- @param pageId - The page ID to render the achievement box for
-- @param frame - The Scribunto frame object for preprocessing
-- @return HTML string containing the achievement box
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.renderAchievementBox(pageId)
function Achievements.renderAchievementBox(pageId, frame)
     if not pageId or pageId == '' then
     if not pageId or pageId == '' then
         return ''
         return ''
     end
     end


     local data = Achievements.loadData()
     local userAchievements = Achievements.getUserAchievements(pageId)
    if not data or not data.user_achievements then
     if #userAchievements == 0 then
        return ''
    end
 
    local key = tostring(pageId)
    local userAchievements = data.user_achievements[key]
    if (not userAchievements or #userAchievements == 0) and key:match("^%d+$") then
        userAchievements = data.user_achievements["n" .. key]
    end
 
     if not userAchievements or #userAchievements == 0 then
         return ''
         return ''
     end
     end
   
    local types = Achievements.loadTypes(frame)
      
      
     -- Build a lookup table for achievement type definitions
     -- Build a lookup table for achievement type definitions
     local typeDefinitions = {}
     local typeDefinitions = {}
     if data and data.achievement_types then
     for _, typeData in ipairs(types) do
        for _, typeData in ipairs(data.achievement_types) do
        if typeData.id and typeData.name then
            if typeData.id and typeData.name then
            typeDefinitions[typeData.id] = {
                typeDefinitions[typeData.id] = {
                name = typeData.name,
                    name = typeData.name,
                tier = typeData.tier or 999
                    tier = typeData.tier or 999
            }
                }
            end
         end
         end
     end
     end


     -- Look for the highest-tier achievement (lowest tier number)
     -- Look for the highest-tier Title achievement (lowest tier number)
     local highestTier = 999
     local highestTier = 999
     local topAchType = nil
     local topAchType = nil
Line 531: Line 556:


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Simple pass-through to track pages (for future expansions)
-- Get page name for a given page ID
-- @param pageId - The page ID to get the name for
-- @return String containing the page name
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.trackPage(pageId, pageName)
function Achievements.getPageName(pageId)
     return true
    if not pageId or pageId == '' then
        return ''
    end
   
    local data = Achievements.loadData()
    if not data or not data.user_achievements then
        return ''
    end
   
    local key = tostring(pageId)
    local userEntry = data.user_achievements[key]
   
    -- Check if entry exists with string key
    if userEntry and userEntry.page_name then
        return userEntry.page_name
    end
   
    -- Try numeric key as fallback
    local numKey = tonumber(key)
    if numKey then
        userEntry = data.user_achievements[numKey]
        if userEntry and userEntry.page_name then
            return userEntry.page_name
        end
    end
   
     return ''
end
end


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Retrieve a specific achievement if present, by type
-- Retrieve a specific achievement if present, by type
-- @param pageId - The page ID to get the achievement for
-- @param achievementType - The achievement type ID to look for
-- @return Achievement object or nil if not found
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.getSpecificAchievement(pageId, achievementType)
function Achievements.getSpecificAchievement(pageId, achievementType)
    debugLog("ACHIEVEMENT-DEBUG: Looking for '" .. tostring(achievementType) ..
            "' in page ID: " .. tostring(pageId))
     if not pageId or not achievementType or pageId == '' then
     if not pageId or not achievementType or pageId == '' then
        debugLog("ACHIEVEMENT-DEBUG: Invalid arguments for getSpecificAchievement")
         return nil
         return nil
     end
     end


     local data = Achievements.loadData()
     local userAchievements = Achievements.getUserAchievements(pageId)
    if not data or not data.user_achievements then
        debugLog("ACHIEVEMENT-DEBUG: No achievement data loaded")
        return nil
    end
 
    local key = tostring(pageId)
    local userAchievements = data.user_achievements[key] or {}
   
    -- If no achievements found under normal ID, try alternative format
    if #userAchievements == 0 and key:match("^%d+$") then
        local altKey = "n" .. key
        debugLog("No achievements under ID '" .. key .. "', trying alternative ID: '" .. altKey .. "'")
        userAchievements = data.user_achievements[altKey] or {}
    end
      
      
     -- Direct lookup for the requested achievement type
     -- Direct lookup for the requested achievement type
     for _, achievement in ipairs(userAchievements) do
     for _, achievementTbl in ipairs(userAchievements) do
         if achievement.type == achievementType then
         if achievementTbl["type"] == achievementType then
            debugLog("FOUND ACHIEVEMENT: " .. achievementType .. " for user " .. key)
local def = Achievements.getAchievementDefinition(achievementType)
             return achievement
            return {
                type    = achievementTbl.type,
                date    = achievementTbl.date or '',
                name    = def and def.name or achievementType,
                category = def and def.category
             }
         end
         end
     end
     end


    debugLog("ACHIEVEMENT-DEBUG: No match found for achievement type: " .. achievementType)
     return nil
     return nil
end
end
Line 579: Line 621:
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Get achievement definition directly from JSON data
-- Get achievement definition directly from JSON data
-- @param achievementType - The achievement type ID to get the definition for
-- @param frame - The Scribunto frame object for preprocessing
-- @return Achievement type definition or nil if not found
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.getAchievementDefinition(achievementType)
function Achievements.getAchievementDefinition(achievementType, frame)
     if not achievementType or achievementType == '' then
     if not achievementType or achievementType == '' then
        debugLog("ACHIEVEMENT-DEF: Empty achievement type")
         return nil
         return nil
     end
     end
      
      
     local data = Achievements.loadData()
     local types = Achievements.loadTypes(frame)
    if not data or not data.achievement_types then
        debugLog("ACHIEVEMENT-DEF: No achievement data loaded")
        return nil
    end
      
      
     -- Direct lookup in achievement_types array
     -- Direct lookup in achievement_types array
     for _, typeData in ipairs(data.achievement_types) do
     for _, typeData in ipairs(types) do
         if typeData.id == achievementType then
         if typeData.id == achievementType then
            debugLog("ACHIEVEMENT-DEF: Found definition for " .. achievementType)
             return typeData
             return typeData
         end
         end
     end
     end
      
      
    debugLog("ACHIEVEMENT-DEF: No definition found for " .. achievementType)
     return nil
     return nil
end
--------------------------------------------------------------------------------
-- Diagnostic Function: List all badges for a page with details
--------------------------------------------------------------------------------
function Achievements.debugBadgesForPage(pageId)
    if not pageId or pageId == '' then
        mw.log("BADGE-DEBUG: Empty page ID")
        return "ERROR: No page ID provided"
    end
    local data = Achievements.loadData()
    if not data then
        mw.log("BADGE-DEBUG: Failed to load achievement data")
        return "ERROR: Failed to load achievement data"
    end
    local key = tostring(pageId)
    local userAchievements = data.user_achievements[key] or {}
   
    -- Check alternate keys if needed
    if #userAchievements == 0 and key:match("^%d+$") then
        local altKey = "n" .. key
        userAchievements = data.user_achievements[altKey] or {}
        if #userAchievements > 0 then
            mw.log("BADGE-DEBUG: Found achievements under alternate key: " .. altKey)
        end
    end
    if #userAchievements == 0 then
        mw.log("BADGE-DEBUG: No achievements found for page ID " .. pageId)
        return "No achievements found for page ID " .. pageId
    end
    -- Build debug report
    local output = {}
    table.insert(output, "=== BADGE DEBUG FOR PAGE " .. pageId .. " ===")
    table.insert(output, "Found " .. #userAchievements .. " achievements")
   
    -- Check each achievement in detail
    for i, achievement in ipairs(userAchievements) do
        local achType = achievement.type or "nil"
        local typeDef = Achievements.getAchievementDefinition(achType)
       
        table.insert(output, "\nACHIEVEMENT " .. i .. ":")
        table.insert(output, "  Type: " .. achType)
       
        if typeDef then
            table.insert(output, "  Name: " .. (typeDef.name or "unnamed"))
            table.insert(output, "  Definition Type: " .. (typeDef.type or "unspecified"))
            table.insert(output, "  Description: " .. (typeDef.description or "none"))
            if typeDef.tier then
                table.insert(output, "  Tier: " .. typeDef.tier)
            end
        else
            table.insert(output, "  WARNING: No type definition found!")
        end
    end
   
    return table.concat(output, "\n")
end
end


Line 668: Line 646:
-- This specifically looks for achievements with type="title"
-- This specifically looks for achievements with type="title"
-- Return the CSS class, readable achievement name, and achievement ID (or empty strings if none found)
-- Return the CSS class, readable achievement name, and achievement ID (or empty strings if none found)
-- @param pageId - The page ID to get the title achievement for
-- @param frame - The Scribunto frame object for preprocessing
-- @return achievementId, displayName, achievementId
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.getTitleAchievement(pageId)
function Achievements.getTitleAchievement(pageId, frame)
     if not pageId or pageId == '' then
     if not pageId or pageId == '' then
        debugLog("Empty page ID provided to getTitleAchievement")
         return nil
         return '', '', ''
     end
     end


     local data = Achievements.loadData()
     local userAchievements = Achievements.getUserAchievements(pageId)
     if not data or not data.user_achievements then
     if #userAchievements == 0 then
        debugLog("No achievement data available in getTitleAchievement")
         return nil
         return '', '', ''
     end
     end


     local key = tostring(pageId)
     local types = Achievements.loadTypes(frame)
    debugLog("Looking up title achievements for page ID: " .. key)
      
      
    -- Try to fetch achievements for this pageId, checking multiple possible key formats
    local userAchievements = {}
    local userAchievementKey = key
   
    -- Try the direct key first
    if data.user_achievements[key] and #data.user_achievements[key] > 0 then
        debugLog("Found achievements directly under key: " .. key)
        userAchievements = data.user_achievements[key]
        userAchievementKey = key
    -- If no achievements found under normal ID, try alternative formats
    elseif key:match("^%d+$") then
        local alternateKeys = {
            "n" .. key,      -- n12345 format
            "page" .. key,    -- page12345 format
            "user" .. key    -- user12345 format
        }
       
        for _, altKey in ipairs(alternateKeys) do
            if data.user_achievements[altKey] and #data.user_achievements[altKey] > 0 then
                debugLog("Found achievements under alternate key: " .. altKey)
                userAchievements = data.user_achievements[altKey]
                userAchievementKey = altKey
                break
            end
        end
    end
    -- Log achievement count and details for all pages consistently
    if #userAchievements > 0 then
        debugLog("Found " .. #userAchievements .. " achievements for page ID " .. key .. " under key " .. userAchievementKey)
        for i, ach in ipairs(userAchievements) do
            debugLog("  Achievement " .. i .. ": type=" .. (ach.type or "nil"))
        end
    else
        debugLog("No achievements found for page ID " .. key .. " under any key")
        return '', '', ''
    end
     -- Build a table of achievement definitions for quick lookup
     -- Build a table of achievement definitions for quick lookup
     local typeDefinitions = {}
     local typeDefinitions = {}
     for _, typeData in ipairs(data.achievement_types) do
     for _, typeData in ipairs(types) do
         typeDefinitions[typeData.id] = typeData
         typeDefinitions[typeData.id] = typeData
        debugLog("Loaded definition for type '" .. typeData.id ..
                "': type=" .. (typeData.type or "nil") ..
                ", name=" .. (typeData.name or "nil"))
     end
     end


     -- Find title achievements only by strictly checking the "type" field
     -- Find title achievements only
     local highestTier = 999
     local highestTier = 999
     local titleAchievement = nil
     local titleAchievement = nil
 
   
     for i, achievement in ipairs(userAchievements) do
     for _, achievement in ipairs(userAchievements) do
         local achType = achievement.type
         local achType = achievement["type"]
         if not achType then
         if achType then
            debugLog("Achievement " .. i .. " missing type property - skipping")
        else
             local typeData = typeDefinitions[achType]
             local typeData = typeDefinitions[achType]
             if not typeData then
             if typeData and typeData["type"] == "title" then
                debugLog("No definition found for achievement type: " .. achType)
                local tier = typeData.tier or 999
            else
                if tier < highestTier then
                -- Check if it's a title type ONLY by examining the "type" property
                    highestTier = tier
                local achDefType = typeData.type
                    titleAchievement = typeData
                debugLog("Checking achievement " .. i .. ": id=" .. achType ..
                      ", definition type=" .. (achDefType or "nil"))
               
                -- Only consider achievements with type="title"
                if achDefType == "title" then
                    debugLog("Found title achievement: " .. achType)
                    local tier = typeData.tier or 999
                    if tier < highestTier then
                        highestTier = tier
                        titleAchievement = typeData
                        debugLog("Using as highest tier title: " .. typeData.id .. " (tier " .. tier .. ")")
                    end
                else
                    debugLog("Skipping non-title achievement: " .. achType .. " (type=" .. (achDefType or "nil") .. ")")
                 end
                 end
             end
             end
Line 765: Line 686:
     end
     end


     if not titleAchievement or not titleAchievement.id then
     return titleAchievement
        debugLog("No valid title achievement found for page ID " .. key)
end
        return '', '', ''
    end


    local cssClass = "achievement-" .. titleAchievement.id
-- Renders a title block with achievement integration
     local displayName = titleAchievement.name or titleAchievement.id or "Award"
function Achievements.renderTitleBlockWithAchievement(args, titleClass, titleText, achievementClass, achievementId, achievementName)
    local achievementId = titleAchievement.id
     titleClass = titleClass or "template-title"
      
      
     debugLog("Using title achievement: " .. cssClass .. " with name: " .. displayName)
     -- Only add achievement attributes if they exist
      
    if achievementClass and achievementClass ~= "" and achievementId and achievementId ~= "" then
    return cssClass, displayName, achievementId
        return string.format(
            '|-\n! colspan="2" class="%s %s" data-achievement-id="%s" data-achievement-name="%s" | %s',
            titleClass, achievementClass, achievementId, achievementName, titleText
        )
     else
        -- Clean row with no achievement data
        return string.format('|-\n! colspan="2" class="%s" | %s', titleClass, titleText)
    end
end
end


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Diagnostic function that can be directly called to troubleshoot JSON loading
-- Generate wikitext category links for a given list of achievements
-- @param achievements - An array of user achievement objects
-- @param frame - The Scribunto frame object
-- @return A string of wikitext category links, e.g., "[[Category:Cat1]][[Category:Cat2]]"
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Achievements.diagnoseJsonLoading()
function Achievements.getCategoryLinks(achievements, frame)
    local output = {}
     if not achievements or #achievements == 0 then
    table.insert(output, "===== ACHIEVEMENT SYSTEM JSON DIAGNOSTICS =====")
         return ""
      
    -- Check MediaWiki version and capabilities
    table.insert(output, "\n== MEDIAWIKI CAPABILITIES ==")
    if mw.loadJsonData then
         table.insert(output, "✓ mw.loadJsonData: Available")
    else
        table.insert(output, "❌ mw.loadJsonData: Not available! MediaWiki may be too old or misconfigured")
     end
     end
   
 
     if mw.text and mw.text.jsonDecode then
     local types = Achievements.loadTypes(frame)
        table.insert(output, "✓ mw.text.jsonDecode: Available")
     local typeDefinitions = {}
     else
    for _, typeData in ipairs(types) do
         table.insert(output, "❌ mw.text.jsonDecode: Not available! This is a critical function")
         typeDefinitions[typeData.id] = typeData
     end
     end
   
 
     -- We don't use Module:JSON anymore, just note that we're using built-in functions
     local categoryLinks = {}
    table.insert(output, "ℹ️ Using MediaWiki's built-in JSON functions")
     local foundCategories = {} -- To prevent duplicate categories
   
 
    -- Check the page configuration
     for _, ach in ipairs(achievements) do
    table.insert(output, "\n== JSON PAGE STATUS ==")
         local achType = ach['type']
     local pageTitle = mw.title.new(ACHIEVEMENT_DATA_PAGE)
         local definition = typeDefinitions[achType]
    if not pageTitle then
        table.insert(output, "❌ Could not create title object for: " .. ACHIEVEMENT_DATA_PAGE)
        return table.concat(output, "\n")
    end
   
    if not pageTitle.exists then
        table.insert(output, "❌ Page does not exist: " .. ACHIEVEMENT_DATA_PAGE)
        return table.concat(output, "\n")
    end
   
    table.insert(output, "✓ Page exists: " .. ACHIEVEMENT_DATA_PAGE)
   
    -- Check the content model
    if pageTitle.contentModel then
        table.insert(output, "Content model: " .. pageTitle.contentModel)
        if pageTitle.contentModel == "json" then
            table.insert(output, "✓ Page has correct content model: 'json'")
        else
            table.insert(output, "❌ Page has INCORRECT content model: '" .. pageTitle.contentModel .. "' (should be 'json')")
        end
     else
        table.insert(output, "⚠ Could not determine content model")
    end
   
    -- Try to fetch page content
    local content = nil
    local contentSuccess, contentResult = pcall(function()
        return pageTitle:getContent()
    end)
   
    if not contentSuccess or not contentResult or contentResult == "" then
         table.insert(output, "❌ Failed to get page content: " .. tostring(contentResult or "Unknown error"))
        return table.concat(output, "\n")
    end
   
    table.insert(output, "✓ Got page content, length: " .. #contentResult)
   
    -- Check page content
    content = contentResult
    local contentPreview = content:sub(1, 50):gsub("\n", "\\n"):gsub("\t", "\\t")
    table.insert(output, "Content preview: \"" .. contentPreview .. "...\"")
   
    if content:match("^%s*{") then
        table.insert(output, "✓ Content starts with { (correct)")
    else
        table.insert(output, "❌ Content does NOT start with { (INCORRECT)")
    end
   
    -- Check for common issues
    if content:match("^<!DOCTYPE") or content:match("^<[Hh][Tt][Mm][Ll]") then
         table.insert(output, "❌ CRITICAL ERROR: Content appears to be HTML, not JSON!")
    elseif content:match("^%s*<") then
        table.insert(output, "❌ CRITICAL ERROR: Content appears to have XML/HTML markup!")
    end
   
    -- Try mw.loadJsonData
    table.insert(output, "\n== TESTING mw.loadJsonData ==")
    local loadJsonSuccess, loadJsonResult = pcall(function()
        return mw.loadJsonData(ACHIEVEMENT_DATA_PAGE)
    end)
   
    if not loadJsonSuccess then
        table.insert(output, "❌ mw.loadJsonData failed: " .. tostring(loadJsonResult or "Unknown error"))
          
          
        -- Analyze error
         if definition and definition.category and definition.category ~= "" and not foundCategories[definition.category] then
        local errorMsg = tostring(loadJsonResult or "")
             table.insert(categoryLinks, "[[Category:" .. definition.category .. "]]")
         if errorMsg:match("content model") then
             foundCategories[definition.category] = true
            table.insert(output, "ERROR CAUSE: Content model issue - page must be set to 'json' model")
        elseif errorMsg:match("JSON decode") or errorMsg:match("syntax") then
            table.insert(output, "ERROR CAUSE: JSON syntax error - check for invalid JSON formatting")
        elseif errorMsg:match("permission") or errorMsg:match("access") then
            table.insert(output, "ERROR CAUSE: Permission/access error - check page permissions")
        end
    else
        table.insert(output, "✓ mw.loadJsonData SUCCESSFUL!")
        table.insert(output, "Data type: " .. type(loadJsonResult))
       
        if type(loadJsonResult) == "table" then
             local keysFound = {}
            for k, _ in pairs(loadJsonResult) do
                table.insert(keysFound, k)
            end
            table.insert(output, "Top-level keys: " .. table.concat(keysFound, ", "))
           
            if loadJsonResult.achievement_types then
                table.insert(output, "✓ Found " .. #loadJsonResult.achievement_types .. " achievement types")
             else
                table.insert(output, "❌ Missing 'achievement_types' array!")
            end
           
            if loadJsonResult.user_achievements then
                local userCount = 0
                for _, _ in pairs(loadJsonResult.user_achievements) do
                    userCount = userCount + 1
                end
                table.insert(output, "✓ Found user achievements for " .. userCount .. " users")
            else
                table.insert(output, "❌ Missing 'user_achievements' object!")
            end
         end
         end
     end
     end
   
 
    -- Try direct JSON decoding
     return table.concat(categoryLinks)
    table.insert(output, "\n== TESTING DIRECT JSON DECODING ==")
   
    -- Use mw.text.jsonDecode
    if mw.text and mw.text.jsonDecode then
        local jsonDecodeSuccess, jsonData = pcall(function()
            return mw.text.jsonDecode(content)
        end)
       
        if jsonDecodeSuccess and jsonData then
            table.insert(output, "✓ mw.text.jsonDecode SUCCESSFUL!")
           
            if jsonData.achievement_types then
                table.insert(output, "✓ Found " .. #jsonData.achievement_types .. " achievement types")
            else
                table.insert(output, "❌ Missing 'achievement_types' array in decoded data!")
            end
        else
            table.insert(output, "❌ mw.text.jsonDecode failed: " .. tostring(jsonData or "Unknown error"))
        end
    else
        table.insert(output, "⚠ Cannot test mw.text.jsonDecode (not available)")
    end
   
    -- Use Module:JSON if available
    if json and json.decode then
        local parseSuccess, parsedData = pcall(function()
            return json.decode(content)
        end)
       
        if parseSuccess and parsedData then
            table.insert(output, "✓ Module:JSON's json.decode SUCCESSFUL!")
           
            if parsedData.achievement_types then
                table.insert(output, "✓ Found " .. #parsedData.achievement_types .. " achievement types")
            else
                table.insert(output, "❌ Missing 'achievement_types' array in decoded data!")
            end
        else
            table.insert(output, "❌ Module:JSON's json.decode failed: " .. tostring(parsedData or "Unknown error"))
        end
    else
        table.insert(output, "⚠ Cannot test Module:JSON (not available)")
    end
   
    -- Add recommendations
    table.insert(output, "\n== RECOMMENDATIONS ==")
    if not loadJsonSuccess then
        table.insert(output, "1. Ensure '" .. ACHIEVEMENT_DATA_PAGE .. "' has content model set to 'json'")
        table.insert(output, "2. Verify the JSON is valid with no syntax errors")
        table.insert(output, "3. Check the page starts with { with no leading whitespace or comments")
    else
        table.insert(output, "✓ JSON loading appears to be working correctly!")
    end
   
     return table.concat(output, "\n")
end
end


return Achievements
return Achievements

Latest revision as of 02:56, 25 August 2025

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

--[[
* Name: AchievementSystem
* Author: Mark W. Datysgeld
* Description: Comprehensive achievement system that manages user badges and titles throughout ICANNWiki, loading data from MediaWiki JSON files and providing rendering functions for Person templates
* Notes: Loads from MediaWiki:AchievementData.json (user assignments) and MediaWiki:AchievementList.json (type definitions). CSS styling defined in Templates.css using achievement-{id} format. Includes caching and fallback mechanisms for robust JSON handling
]]

---@class UserAchievement
---@field type string
---@field date? string

local Achievements = {}

--------------------------------------------------------------------------------
-- JSON Handling
--------------------------------------------------------------------------------
-- Helper function to ensure we get an array
local function ensureArray(value)
    if type(value) ~= "table" then
        return {}
    end
    
    -- Check if it's an array-like table
    local isArray = true
    local count = 0
    for _ in pairs(value) do
        count = count + 1
    end
    
    -- If it has no numeric indices or is empty, return empty array
    if count == 0 then
        return {}
    end
    
    -- If it's a single string, wrap it in an array
    if count == 1 and type(value[1]) == "string" then
        return {value[1]}
    end
    
    -- If it has a single non-array value, try to convert it to an array
    if count == 1 and next(value) and type(next(value)) ~= "number" then
        local k, v = next(value)
        if type(v) == "string" then
            return {v}
        end
    end
    
    -- Return the original table if it seems to be an array
    return value
end

-- Use MediaWiki's built-in JSON functions directly
local function jsonDecode(jsonString)
    if not jsonString then return nil end
    
    if mw.text and mw.text.jsonDecode then
        local success, result = pcall(function()
            -- Use WITHOUT PRESERVE_KEYS flag to ensure proper array handling
            return mw.text.jsonDecode(jsonString)
        end)
        
        if success and result then
            return result
        end
    end
    
    return nil
end

-- Simple HTML encode fallback
local function htmlEncode(str)
    if mw.text and mw.text.htmlEncode then
        return mw.text.htmlEncode(str or '')
    else
        return (str or '')
            :gsub('&', '&amp;')
            :gsub('<', '&lt;')
            :gsub('>', '&gt;')
            :gsub('"', '&quot;')
    end
end

--------------------------------------------------------------------------------
-- Configuration, Default Data, and Cache
--------------------------------------------------------------------------------
local ACHIEVEMENT_DATA_PAGE = 'MediaWiki:AchievementData.json'
local ACHIEVEMENT_LIST_PAGE = 'MediaWiki:AchievementList.json'
local dataCache = nil
local typesCache = nil

local DEFAULT_DATA = {
    schema_version = 2,
    last_updated = os.date('!%Y-%m-%dT%H:%M:%SZ'),
    achievement_types = {},
    user_achievements = {},
}

--------------------------------------------------------------------------------
-- Load achievement types from the JSON page
-- @param frame - The Scribunto frame object for preprocessing
-- @return Array of achievement type definitions
--------------------------------------------------------------------------------
function Achievements.loadTypes(frame)
    -- Use the request-level cache if we already loaded data once
    if typesCache then
        return typesCache
    end

    local success, types = pcall(function()
        -- Get the JSON content using frame:preprocess if available
        local jsonText
        if frame and type(frame) == "table" and frame.preprocess then
            -- Make sure frame is valid and has preprocess method
            local preprocessSuccess, preprocessResult = pcall(function()
                return frame:preprocess('{{MediaWiki:AchievementList.json}}')
            end)
            
            if preprocessSuccess and preprocessResult then
                jsonText = preprocessResult
            end
        end
        
        -- If we couldn't get JSON from frame:preprocess, fall back to direct content loading
        if not jsonText then
            -- Try using mw.loadJsonData first (preferred method)
            if mw.loadJsonData then
                local loadJsonSuccess, jsonData = pcall(function()
                    return mw.loadJsonData(ACHIEVEMENT_LIST_PAGE)
                end)
                
                if loadJsonSuccess and jsonData and type(jsonData) == 'table' and jsonData.achievement_types then
                    return jsonData.achievement_types
                end
            end
            
            -- Direct content loading approach as fallback
            local pageTitle = mw.title.new(ACHIEVEMENT_LIST_PAGE)
            if pageTitle and pageTitle.exists then
                -- Get raw content from the wiki page
                local contentSuccess, content = pcall(function()
                    return pageTitle:getContent()
                end)
                
                if contentSuccess and content and content ~= "" then
                    -- Remove any BOM or leading whitespace that might cause issues
                    content = content:gsub("^%s+", "")
                    if content:byte(1) == 239 and content:byte(2) == 187 and content:byte(3) == 191 then
                        content = content:sub(4)
                    end
                    
                    jsonText = content
                    
                    -- Try different JSON decode approaches
                    if jsonText and mw.text and mw.text.jsonDecode then
                        -- First try WITHOUT PRESERVE_KEYS flag (standard approach)
                        local jsonDecodeSuccess, jsonData = pcall(function()
                            return mw.text.jsonDecode(jsonText)
                        end)
                        
                        if jsonDecodeSuccess and jsonData and jsonData.achievement_types then
                            return jsonData.achievement_types
                        end
                        
                        -- If that failed, try with JSON_TRY_FIXING flag
                        jsonDecodeSuccess, jsonData = pcall(function()
                            return mw.text.jsonDecode(jsonText, mw.text.JSON_TRY_FIXING)
                        end)
                        
                        if jsonDecodeSuccess and jsonData and jsonData.achievement_types then
                            return jsonData.achievement_types
                        end
                    end
                end
            end
            
            -- If we couldn't load from AchievementList.json, fall back to AchievementData.json
            local data = Achievements.loadData(frame)
            if data and data.achievement_types then
                return data.achievement_types
            end
        else
            -- We have jsonText from frame:preprocess, try to decode it
            if jsonText and mw.text and mw.text.jsonDecode then
                -- First try WITHOUT PRESERVE_KEYS flag (standard approach)
                local jsonDecodeSuccess, jsonData = pcall(function()
                    return mw.text.jsonDecode(jsonText)
                end)
                
                if jsonDecodeSuccess and jsonData and jsonData.achievement_types then
                    return jsonData.achievement_types
                end
                
                -- If that failed, try with JSON_TRY_FIXING flag
                jsonDecodeSuccess, jsonData = pcall(function()
                    return mw.text.jsonDecode(jsonText, mw.text.JSON_TRY_FIXING)
                end)
                
                if jsonDecodeSuccess and jsonData and jsonData.achievement_types then
                    return jsonData.achievement_types
                end
            end
            
            -- If we couldn't decode the JSON, fall back to AchievementData.json
            local data = Achievements.loadData(frame)
            if data and data.achievement_types then
                return data.achievement_types
            end
        end
        
        -- As an absolute last resort, return an empty array
        return {}
    end)

    if not success or not types then
        -- If there was an error, fall back to AchievementData.json
        local data = Achievements.loadData(frame)
        if data and data.achievement_types then
            typesCache = data.achievement_types
            return typesCache
        end
        types = {}
    end

    typesCache = types
    return types
end

--------------------------------------------------------------------------------
-- Load achievement data from the JSON page
-- @param frame - The Scribunto frame object for preprocessing
-- @return Table containing the full achievement data
--------------------------------------------------------------------------------
function Achievements.loadData(frame)
    -- Use the request-level cache if we already loaded data once
    if dataCache then
        return dataCache
    end

    local success, data = pcall(function()
        -- Get the JSON content using frame:preprocess if available
        local jsonText
        if frame and type(frame) == "table" and frame.preprocess then
            -- Make sure frame is valid and has preprocess method
            local preprocessSuccess, preprocessResult = pcall(function()
                return frame:preprocess('{{MediaWiki:AchievementData.json}}')
            end)
            
            if preprocessSuccess and preprocessResult then
                jsonText = preprocessResult
            end
        end
        
        -- If we couldn't get JSON from frame:preprocess, fall back to direct content loading
        if not jsonText then
            -- Try using mw.loadJsonData first (preferred method)
            if mw.loadJsonData then
                local loadJsonSuccess, jsonData = pcall(function()
                    return mw.loadJsonData(ACHIEVEMENT_DATA_PAGE)
                end)
                
                if loadJsonSuccess and jsonData and type(jsonData) == 'table' then
                    return jsonData
                end
            end
            
            -- Direct content loading approach as fallback
            local pageTitle = mw.title.new(ACHIEVEMENT_DATA_PAGE)
            if not pageTitle or not pageTitle.exists then
                return DEFAULT_DATA
            end
            
            -- Get raw content from the wiki page
            local contentSuccess, content = pcall(function()
                return pageTitle:getContent()
            end)
            
            if contentSuccess and content and content ~= "" then
                -- Remove any BOM or leading whitespace that might cause issues
                content = content:gsub("^%s+", "")
                if content:byte(1) == 239 and content:byte(2) == 187 and content:byte(3) == 191 then
                    content = content:sub(4)
                end
                
                jsonText = content
            else
                return DEFAULT_DATA
            end
        end
        
        -- Try different JSON decode approaches
        if jsonText and mw.text and mw.text.jsonDecode then
            -- First try WITHOUT PRESERVE_KEYS flag (standard approach)
            local jsonDecodeSuccess, jsonData = pcall(function()
                return mw.text.jsonDecode(jsonText)
            end)
            
            if jsonDecodeSuccess and jsonData then
                return jsonData
            end
            
            -- If that failed, try with JSON_TRY_FIXING flag
            jsonDecodeSuccess, jsonData = pcall(function()
                return mw.text.jsonDecode(jsonText, mw.text.JSON_TRY_FIXING)
            end)
            
            if jsonDecodeSuccess and jsonData then
                return jsonData
            end
        end
        -- As an absolute last resort, use local default data
        return DEFAULT_DATA
    end)

    if not success or not data then
        data = DEFAULT_DATA
    end

    dataCache = data
    return data
end

--------------------------------------------------------------------------------
-- Get user achievements
-- @param pageId - The page ID to get achievements for
-- @return Array of achievement objects for the specified page
--------------------------------------------------------------------------------
local userAchievementsCache = {}

---@return UserAchievement[]
function Achievements.getUserAchievements(pageId)
    if not pageId or pageId == '' then
        return {}
    end
    
    -- Check cache first
    local cacheKey = tostring(pageId)
    if userAchievementsCache[cacheKey] then
        return userAchievementsCache[cacheKey]
    end

    local data = Achievements.loadData()
    if not data or not data.user_achievements then
        return {}
    end

    local key = cacheKey
    local userEntry = data.user_achievements[key]
    
    -- If found with string key, return achievements
    if userEntry and userEntry.achievements then
        local achievements = ensureArray(userEntry.achievements)
        userAchievementsCache[cacheKey] = achievements
        return achievements
    end
    
    -- Try numeric key as fallback
    local numKey = tonumber(key)
    if numKey then
        userEntry = data.user_achievements[numKey]
        if userEntry and userEntry.achievements then
            local achievements = ensureArray(userEntry.achievements)
            userAchievementsCache[cacheKey] = achievements
            return achievements
        end
    end
    
    -- Cache empty result to avoid repeated lookups
    userAchievementsCache[cacheKey] = {}
    return {}
end

--------------------------------------------------------------------------------
-- Check if a page/user has any achievements
-- @param pageId - The page ID to check
-- @return Boolean indicating if the page has any achievements
--------------------------------------------------------------------------------
function Achievements.hasAchievements(pageId)
    if not pageId or pageId == '' then
        return false
    end

    local userAchievements = Achievements.getUserAchievements(pageId)
    return #userAchievements > 0
end

--------------------------------------------------------------------------------
-- Get all badge-type achievements for a user
-- @param pageId - The page ID to check
-- @param frame - The Scribunto frame object for preprocessing
-- @return Array of badge achievement objects
--------------------------------------------------------------------------------
function Achievements.getBadgeAchievements(pageId, frame)
    if not pageId or pageId == '' then
        return {}
    end

    local userAchievements = Achievements.getUserAchievements(pageId)
    if #userAchievements == 0 then
        return {}
    end

    local types = Achievements.loadTypes(frame)
    
    -- Build a lookup table for achievement types for efficient access
    local typeDefinitions = {}
    for _, typeData in ipairs(types) do
        if typeData.id and typeData.type then
            typeDefinitions[typeData.id] = typeData
        end
    end
    
    local badgeAchievements = {}
    -- Filter user achievements to only include badge types
    for _, achievementTbl in ipairs(userAchievements) do
        local achType = achievementTbl['type']
        if achType and typeDefinitions[achType] and typeDefinitions[achType]['type'] == "badge" then
                local newAchievement = {
                    type = achType,
                    date = achievementTbl['date'] or '',
                    name = typeDefinitions[achType].name or achType,
                    category = typeDefinitions[achType].category
                }
            table.insert(badgeAchievements, newAchievement)
        end
    end

    return badgeAchievements
end

--------------------------------------------------------------------------------
-- Get a user-friendly name for a given achievement type
-- @param achievementType - The achievement type ID
-- @param frame - The Scribunto frame object for preprocessing
-- @return String containing the user-friendly name
--------------------------------------------------------------------------------
function Achievements.getAchievementName(achievementType, frame)
    if not achievementType or achievementType == '' then
        return 'Unknown'
    end

    local types = Achievements.loadTypes(frame)
    
    -- Try to match achievement ID
    for _, typeData in ipairs(types) do
        if typeData.id == achievementType then
            if typeData.name and typeData.name ~= "" then
                return typeData.name
            else
                return achievementType
            end
        end
    end

    return achievementType
end

--------------------------------------------------------------------------------
-- Find the top-tier Title achievement for the user (lowest tier number)
-- Return the CSS class and the readable achievement name
-- @param pageId - The page ID to get the title achievement for
-- @param frame - The Scribunto frame object for preprocessing
-- @return CSS class, display name
--------------------------------------------------------------------------------
function Achievements.getTitleClass(pageId, frame)
    if not pageId or pageId == '' then
        return '', ''
    end

    local userAchievements = Achievements.getUserAchievements(pageId)
    if #userAchievements == 0 then
        return '', ''
    end

    local types = Achievements.loadTypes(frame)
    local highestTier = 999
    local highestAchievement = nil

    for _, achievement in ipairs(userAchievements) do
        local achType = achievement["type"]
        
        for _, typeData in ipairs(types) do
            if typeData.id == achType then
                local tier = typeData.tier or 999
                if tier < highestTier then
                    highestTier = tier
                    highestAchievement = typeData
                end
            end
        end
    end

    if not highestAchievement or not highestAchievement.id then
        return '', ''
    end

    local cssClass = "achievement-" .. highestAchievement.id
    local displayName = highestAchievement.name or highestAchievement.id or "Award"
    
    return cssClass, displayName
end

--------------------------------------------------------------------------------
-- Renders a box with the top-tier achievement for the user
-- @param pageId - The page ID to render the achievement box for
-- @param frame - The Scribunto frame object for preprocessing
-- @return HTML string containing the achievement box
--------------------------------------------------------------------------------
function Achievements.renderAchievementBox(pageId, frame)
    if not pageId or pageId == '' then
        return ''
    end

    local userAchievements = Achievements.getUserAchievements(pageId)
    if #userAchievements == 0 then
        return ''
    end
    
    local types = Achievements.loadTypes(frame)
    
    -- Build a lookup table for achievement type definitions
    local typeDefinitions = {}
    for _, typeData in ipairs(types) do
        if typeData.id and typeData.name then
            typeDefinitions[typeData.id] = {
                name = typeData.name,
                tier = typeData.tier or 999
            }
        end
    end

    -- Look for the highest-tier Title achievement (lowest tier number)
    local highestTier = 999
    local topAchType = nil

    for _, achievement in ipairs(userAchievements) do
        local achType = achievement.type
        if typeDefinitions[achType] and typeDefinitions[achType].tier < highestTier then
            highestTier = typeDefinitions[achType].tier
            topAchType = achType
        end
    end

    -- If we found an achievement, render it
    if topAchType and typeDefinitions[topAchType] then
        local achName = typeDefinitions[topAchType].name or topAchType
        
        return string.format(
            '<div class="achievement-box-simple" data-achievement-type="%s">%s</div>',
            topAchType,
            htmlEncode(achName)
        )
    end

    return ''
end

--------------------------------------------------------------------------------
-- Get page name for a given page ID
-- @param pageId - The page ID to get the name for
-- @return String containing the page name
--------------------------------------------------------------------------------
function Achievements.getPageName(pageId)
    if not pageId or pageId == '' then
        return ''
    end
    
    local data = Achievements.loadData()
    if not data or not data.user_achievements then
        return ''
    end
    
    local key = tostring(pageId)
    local userEntry = data.user_achievements[key]
    
    -- Check if entry exists with string key
    if userEntry and userEntry.page_name then
        return userEntry.page_name
    end
    
    -- Try numeric key as fallback
    local numKey = tonumber(key)
    if numKey then
        userEntry = data.user_achievements[numKey]
        if userEntry and userEntry.page_name then
            return userEntry.page_name
        end
    end
    
    return ''
end

--------------------------------------------------------------------------------
-- Retrieve a specific achievement if present, by type
-- @param pageId - The page ID to get the achievement for
-- @param achievementType - The achievement type ID to look for
-- @return Achievement object or nil if not found
--------------------------------------------------------------------------------
function Achievements.getSpecificAchievement(pageId, achievementType)
    if not pageId or not achievementType or pageId == '' then
        return nil
    end

    local userAchievements = Achievements.getUserAchievements(pageId)
    
    -- Direct lookup for the requested achievement type
    for _, achievementTbl in ipairs(userAchievements) do
        if achievementTbl["type"] == achievementType then
local def = Achievements.getAchievementDefinition(achievementType)
            return {
                type     = achievementTbl.type,
                date     = achievementTbl.date or '',
                name     = def and def.name or achievementType,
                category = def and def.category
            }
        end
    end

    return nil
end

--------------------------------------------------------------------------------
-- Get achievement definition directly from JSON data
-- @param achievementType - The achievement type ID to get the definition for
-- @param frame - The Scribunto frame object for preprocessing
-- @return Achievement type definition or nil if not found
--------------------------------------------------------------------------------
function Achievements.getAchievementDefinition(achievementType, frame)
    if not achievementType or achievementType == '' then
        return nil
    end
    
    local types = Achievements.loadTypes(frame)
    
    -- Direct lookup in achievement_types array
    for _, typeData in ipairs(types) do
        if typeData.id == achievementType then
            return typeData
        end
    end
    
    return nil
end

--------------------------------------------------------------------------------
-- Find and return title achievement for the user if one exists
-- This specifically looks for achievements with type="title"
-- Return the CSS class, readable achievement name, and achievement ID (or empty strings if none found)
-- @param pageId - The page ID to get the title achievement for
-- @param frame - The Scribunto frame object for preprocessing
-- @return achievementId, displayName, achievementId
--------------------------------------------------------------------------------
function Achievements.getTitleAchievement(pageId, frame)
    if not pageId or pageId == '' then
        return nil
    end

    local userAchievements = Achievements.getUserAchievements(pageId)
    if #userAchievements == 0 then
        return nil
    end

    local types = Achievements.loadTypes(frame)
    
    -- Build a table of achievement definitions for quick lookup
    local typeDefinitions = {}
    for _, typeData in ipairs(types) do
        typeDefinitions[typeData.id] = typeData
    end

    -- Find title achievements only
    local highestTier = 999
    local titleAchievement = nil
    
    for _, achievement in ipairs(userAchievements) do
        local achType = achievement["type"]
        if achType then
            local typeData = typeDefinitions[achType]
            if typeData and typeData["type"] == "title" then
                local tier = typeData.tier or 999
                if tier < highestTier then
                    highestTier = tier
                    titleAchievement = typeData
                end
            end
        end
    end

    return titleAchievement
end

-- Renders a title block with achievement integration
function Achievements.renderTitleBlockWithAchievement(args, titleClass, titleText, achievementClass, achievementId, achievementName)
    titleClass = titleClass or "template-title"
    
    -- Only add achievement attributes if they exist
    if achievementClass and achievementClass ~= "" and achievementId and achievementId ~= "" then
        return string.format(
            '|-\n! colspan="2" class="%s %s" data-achievement-id="%s" data-achievement-name="%s" | %s',
            titleClass, achievementClass, achievementId, achievementName, titleText
        )
    else
        -- Clean row with no achievement data
        return string.format('|-\n! colspan="2" class="%s" | %s', titleClass, titleText)
    end
end

--------------------------------------------------------------------------------
-- Generate wikitext category links for a given list of achievements
-- @param achievements - An array of user achievement objects
-- @param frame - The Scribunto frame object
-- @return A string of wikitext category links, e.g., "[[Category:Cat1]][[Category:Cat2]]"
--------------------------------------------------------------------------------
function Achievements.getCategoryLinks(achievements, frame)
    if not achievements or #achievements == 0 then
        return ""
    end

    local types = Achievements.loadTypes(frame)
    local typeDefinitions = {}
    for _, typeData in ipairs(types) do
        typeDefinitions[typeData.id] = typeData
    end

    local categoryLinks = {}
    local foundCategories = {} -- To prevent duplicate categories

    for _, ach in ipairs(achievements) do
        local achType = ach['type']
        local definition = typeDefinitions[achType]
        
        if definition and definition.category and definition.category ~= "" and not foundCategories[definition.category] then
            table.insert(categoryLinks, "[[Category:" .. definition.category .. "]]")
            foundCategories[definition.category] = true
        end
    end

    return table.concat(categoryLinks)
end

return Achievements