Module:Infobox item

Revision as of 16:56, 2 March 2026 by Monster Domosed (talk | contribs) (Monster Domosed moved page Module:Infobox Item to Module:Infobox item: Misspelled title)

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

local p = {}
local lang = require "Module:Lang"
local util_module = require "Module:Utilities"
local data = mw.loadJsonData("Data:ItemCards.json")
local stat_links = mw.loadJsonData("Data:StatLinks.json")

-- Local references for hot-path globals
local format = string.format
local concat = table.concat
local insert = table.insert
local ipairs = ipairs
local pairs = pairs
local tonumber = tonumber
local tostring = tostring
local type = type

-- Pre-computed constants
local STATUS_FMT = "[[{{#invoke:Lang|get_string|Citadel_%s}}]]"
    .. " [[{{#invoke:Lang|get_string|Citadel_StatusEffect}}]]"

-- Spirit damage constants
local SPIRIT_ICON = "[[File:Spirit_damage.png|12px]]"
local SPIRIT_COLOR = "#bc8ee8"
local SPIRIT_LINK = "Spirit Damage"

-- Label key remapping table (replaces if/elseif chain)
local LABEL_KEY_REMAP = {
    BuildUpPerShot = "BuildupPerShot",
    DotDuration    = "DOTDuration",
}

-- Suffix pairs for lang data existence checks
local LANG_SUFFIX_PAIRS = {
    { "_label",          "_Label" },
    { "_prefix",         "_Prefix" },
    { "_postfix",        "_Postfix" },
    { "_postvalue_label", "_Postvalue_Label" },
}

--------------------------------------------------------------------------------
-- Caches
--------------------------------------------------------------------------------

local lang_cache = {}
local info_sections_cache = setmetatable({}, { __mode = "k" }) -- weak keys

local function cached_get_string(key)
    local v = lang_cache[key]
    if v ~= nil then return v or nil end -- false sentinel → nil
    local result = lang.get_string(key)
    lang_cache[key] = result or false
    return result
end

local conditional_label -- lazily initialised

--------------------------------------------------------------------------------
-- Utility helpers
--------------------------------------------------------------------------------

local function get_lang_pair(base_key, suffix1, suffix2)
    local v1 = cached_get_string(base_key .. suffix1)
    if v1 and v1 ~= "" then return v1 end
    local v2 = cached_get_string(base_key .. suffix2)
    if v2 and v2 ~= "" then return v2 end
    return ""
end

--------------------------------------------------------------------------------
-- Data access helpers
--------------------------------------------------------------------------------

local function get_json_item(name)
    local direct = data[name]
    if direct and not direct.IsDisabled then return direct end

    local fallback
    for _, v in pairs(data) do
        if v.Name == name then
            if not v.IsDisabled then return v end
            fallback = fallback or v
        end
    end
    return fallback
end

local function get_info_sections(item)
    local cached = info_sections_cache[item]
    if cached then return cached end

    local sections = {}
    local i = 1
    while item["Info" .. i] do
        sections[i] = item["Info" .. i]
        i = i + 1
    end
    info_sections_cache[item] = sections
    return sections
end

local function find_property_obj(item, prop_key)
    for _, section in ipairs(get_info_sections(item)) do
        for _, obj in ipairs(section.Main or {}) do
            if obj.Key == prop_key then return obj end
        end
        for _, obj in ipairs(section.Alt or {}) do
            if obj.Key == prop_key then return obj end
        end
    end
    local other = item.Other
    return other and other[prop_key] or nil
end

local function is_property_in_lang_data(prop, loc_override)
    local has_override = loc_override and loc_override ~= prop
    for _, pair in ipairs(LANG_SUFFIX_PAIRS) do
        if cached_get_string(prop .. pair[1]) or cached_get_string(prop .. pair[2]) then
            return true
        end
        if has_override and (
            cached_get_string(loc_override .. pair[1]) or
            cached_get_string(loc_override .. pair[2])
        ) then
            return true
        end
    end
    return false
end

local function get_component_of_sorted(item_input)
    local target_key
    if data[item_input] then
        target_key = item_input
    else
        for k, v in pairs(data) do
            if v.Name == item_input and not v.IsDisabled then
                target_key = k
                break
            end
        end
    end
    if not target_key then return {} end

    local parents = {}
    for key, item in pairs(data) do
        if not item.IsDisabled and type(item.Components) == "table" then
            for _, comp in ipairs(item.Components) do
                if comp == target_key then
                    insert(parents, key)
                    break
                end
            end
        end
    end

    table.sort(parents, function(a, b)
        return (tonumber(data[a] and data[a].Tier) or 0)
             < (tonumber(data[b] and data[b].Tier) or 0)
    end)
    return parents
end

--------------------------------------------------------------------------------
-- Shared formatting primitives
--------------------------------------------------------------------------------

local function resolve_label_key(prop_key, loc_override)
    local base = (loc_override or prop_key):gsub("^#", "")
    return LABEL_KEY_REMAP[base] or base
end

local function resolve_prefix(prefix, numeric_val)
    if prefix == "{s:sign}" then
        return numeric_val >= 0 and "+" or ""
    end
    return prefix
end

local function resolve_suffix(postfix, css_type)
    if postfix == "HP/s" then return "&#32;" .. postfix end
    return postfix
end

local function append_label(val_str, prop_key, label, label_color, link_override)
    if label == "" then return val_str end
    local display_label
    local link_page = link_override or stat_links[prop_key]
    if link_page then
        if link_page == label then
            display_label = "[[" .. label .. "]]"
        else
            display_label = "[[" .. link_page .. "|" .. label .. "]]"
        end
    else
        display_label = label
    end
    if label_color then
        display_label = '<span style="color:' .. label_color .. '">'
            .. display_label .. '</span>'
    end
    return val_str .. " " .. display_label
end

local function append_conditional(val_str, allow_conditional, usage_flags)
    if not allow_conditional then return val_str end
    if usage_flags ~= "ConditionallyApplied"
       and usage_flags ~= "ConditionallyEnemyApplied" then
        return val_str
    end
    if not conditional_label then
        conditional_label = format(
            ' <span style="color:#C0C0C0">(%s)</span>',
            lang.get_string("Citadel_Shop_ConditionalAttribute")
        )
    end
    return val_str .. conditional_label
end

local function extract_numeric(value)
    if value == nil or value == 0 or value == "" then return nil end
    local n = tonumber(tostring(value):match("^-?%d+%.?%d*"))
    return (n and n ~= 0) and n or nil
end

--------------------------------------------------------------------------------
-- Spirit damage detection helper
--------------------------------------------------------------------------------

local function is_spirit_damage(prop_key, css_type)
    return prop_key == "Damage" and css_type == "tech_damage"
end

--------------------------------------------------------------------------------
-- Core formatting: non-enhanced
--------------------------------------------------------------------------------

local function format_value(prop_key, value, css_type, loc_override,
                            skip_label, allow_conditional, usage_flags, scale_info)
    local numeric_val = extract_numeric(value)
    if not numeric_val then return nil end

    local label_key = resolve_label_key(prop_key, loc_override)
    local label   = skip_label and "" or get_lang_pair(label_key, "_label", "_Label")
    local prefix  = get_lang_pair(label_key, "_prefix", "_Prefix")
    local postfix = get_lang_pair(label_key, "_postfix", "_Postfix")

    if prefix == "" and postfix == "" and label == "" then return nil end

    prefix = resolve_prefix(prefix, numeric_val)
    local suffix = resolve_suffix(postfix, css_type)

    -- Compose numeric + scaling first
    local val_str = tostring(numeric_val)
    if scale_info and scale_info.Value and scale_info.Value ~= 0 then
        local scale_val = util_module.round_to_sig_fig(scale_info.Value, 2)
        local tmpl = scale_info.Type == "power_increase" and "Boon" or "Ss"
        val_str = val_str .. " " .. mw.getCurrentFrame():expandTemplate{
            title = tmpl, args = { scale_val }
        }
    end

    -- Then prepend prefix
    if prefix ~= "" then val_str = prefix .. val_str end
    -- Then append postfix
    if suffix ~= "" and not val_str:find(suffix, 1, true) then
        val_str = val_str .. suffix
    end

    -- Spirit damage: prepend icon before the value
    local spirit = is_spirit_damage(prop_key, css_type)
    if spirit then
        val_str = SPIRIT_ICON .. " " .. val_str
    end

    val_str = append_label(val_str, label_key, label,
        spirit and SPIRIT_COLOR or nil,
        spirit and SPIRIT_LINK or nil)
    return append_conditional(val_str, allow_conditional, usage_flags)
end

--------------------------------------------------------------------------------
-- Core formatting: enhanced
--------------------------------------------------------------------------------

local function format_value_enhanced(item_name, prop_key, value, css_type,
                                     loc_override, skip_label,
                                     allow_conditional, usage_flags)
    local numeric_val = extract_numeric(value)
    if not numeric_val then return nil end

    local label_key = resolve_label_key(prop_key, loc_override)

    -- Enhanced requires at least one lang token to exist
    local has_lang = false
    for _, pair in ipairs(LANG_SUFFIX_PAIRS) do
        if cached_get_string(label_key .. pair[1])
           or cached_get_string(label_key .. pair[2]) then
            has_lang = true
            break
        end
    end
    if not has_lang then return nil end

    local label   = skip_label and "" or get_lang_pair(label_key, "_label", "_Label")
    local prefix  = get_lang_pair(label_key, "_prefix", "_Prefix")
    local postfix = get_lang_pair(label_key, "_postfix", "_Postfix")

    if prefix == "" and postfix == "" and label == "" then return nil end

    prefix = resolve_prefix(prefix, numeric_val)
    local suffix = resolve_suffix(postfix, css_type)

    -- Build Enhanced invoke
    local extras = {}
    if prefix ~= "" then insert(extras, "prefix=" .. prefix) end
    if suffix ~= "" and suffix ~= "%" then insert(extras, "suffix=" .. suffix) end
    insert(extras, "noicon=true")

    local val_str = format(
        "{{#invoke:Enhanced|render|%s|%s|%s}}",
        item_name, prop_key, concat(extras, "|")
    )

    -- Append postfix if not already present
    if postfix ~= "" and postfix ~= "%" and not val_str:find(postfix, 1, true) then
        val_str = val_str .. (postfix == "HP/s" and (" " .. postfix) or postfix)
    end

    -- Spirit damage: prepend icon before the value
    local spirit = is_spirit_damage(prop_key, css_type)
    if spirit then
        val_str = SPIRIT_ICON .. " " .. val_str
    end

    val_str = append_label(val_str, label_key, label,
        spirit and SPIRIT_COLOR or nil,
        spirit and SPIRIT_LINK or nil)
    return append_conditional(val_str, allow_conditional, usage_flags)
end
--------------------------------------------------------------------------------
-- Tooltip builder helpers
--------------------------------------------------------------------------------

local function format_section_cooldown(section, item_name, enhanced)
    local result = {}
    local cd, cu = section.Cooldown, section.ChargeUp
    if cd and cd ~= 0 then
        result.cooldown = enhanced
            and format_value_enhanced(item_name, "AbilityCooldown", cd, nil, nil, true, false, nil)
            or  format_value("AbilityCooldown", cd, nil, nil, true, false, nil, nil)
    end
    if cu and cu ~= 0 then
        result.chargeup = enhanced
            and format_value_enhanced(item_name, "AbilityChargeUpTime", cu, nil, nil, true, false, nil)
            or  format_value("AbilityChargeUpTime", cu, nil, nil, true, false, nil, nil)
    end
    return result
end

local function process_stats(lines, fmt, counter, start_index, prop_list,
                             item_name, seen, formatter)
    local stat_index = start_index
    for _, prop_obj in ipairs(prop_list or {}) do
        local key = prop_obj.Key
        if not seen[key] and (
            key:match("^StatusEffect")
            or is_property_in_lang_data(key, prop_obj.LocTokenOverride)
        ) then
            local val = formatter(prop_obj)
            if val then
                insert(lines, format(fmt, counter, stat_index, val))
                stat_index = stat_index + 1
                seen[key] = true
            end
        end
    end
    return stat_index
end
--------------------------------------------------------------------------------
-- Unified tooltip builder (handles both default and enhanced modes)
--------------------------------------------------------------------------------
local function build_tooltip_impl(frame, enhanced)
    local item_name = frame.args[1]
    if not item_name then return "Item name missing" end

    local item = get_json_item(item_name)
    if not item then return "Item not found" end

    local ItemData = require("Module:ItemData")
    local lines = { "{{Infobox item" }

    if enhanced then
        insert(lines, "| enhanced = true")
    end
    insert(lines, "| item_name = " .. item_name)

    if item.StreetBrawl == true then
        insert(lines, "| street_brawl = true")
    end

    local sections = get_info_sections(item)

    ------------------------------------------------------------------
    -- Innate stats
    ------------------------------------------------------------------
    local innate_index = 1
    for _, section in ipairs(sections) do
        if section.Type == "Innate" then
            for _, obj in ipairs(section.Main or {}) do

                if is_property_in_lang_data(obj.Key, obj.LocTokenOverride) then
                    local val
                    if enhanced then
                        val = format_value_enhanced(item_name, obj.Key, obj.Value, obj.Type, obj.LocTokenOverride, nil, false, obj.UsageFlags)
                    else
                        val = format_value(obj.Key, obj.Value, obj.Type, obj.LocTokenOverride, false, false, obj.UsageFlags, obj.Scale)
                    end
                    if val then
                        insert(lines, format("| item_stat%d = %s", innate_index, val))
                        innate_index = innate_index + 1
                    end
                end
            end
            for _, obj in ipairs(section.Alt or {}) do

                if is_property_in_lang_data(obj.Key, obj.LocTokenOverride) then
                    local val
                    if enhanced then
                        val = format_value_enhanced(
                            item_name, obj.Key, obj.Value, obj.Type,
                            obj.LocTokenOverride, nil, false, obj.UsageFlags
                        )
                    else
                        val = format_value(
                            obj.Key, obj.Value, obj.Type, obj.LocTokenOverride,
                            false, false, obj.UsageFlags, obj.Scale
                        )
                    end
                    if val then
                        insert(lines, format("| item_stat%d = %s", innate_index, val))
                        innate_index = innate_index + 1
                    end
                end
            end
        end
    end

    ------------------------------------------------------------------
    -- Build formatters once (closures capture item_name)
    ------------------------------------------------------------------
    local main_formatter, alt_formatter

    if enhanced then
        main_formatter = function(obj)
            if obj.Key:match("^StatusEffect") then
                return format(STATUS_FMT, obj.Key)
            end

            return format_value_enhanced(
                item_name, obj.Key, obj.Value, obj.Type,
                obj.LocTokenOverride, false, true, obj.UsageFlags
            )
        end
        alt_formatter = function(obj)

            return format_value_enhanced(
                item_name, obj.Key, obj.Value, obj.Type,
                obj.LocTokenOverride, nil, false, obj.UsageFlags
            )
        end
    else
		main_formatter = function(obj)
		    if obj.Key:match("^StatusEffect") then
		        return format(STATUS_FMT, obj.Key)
		    end

		    return format_value(
		        obj.Key, obj.Value, obj.Type, obj.LocTokenOverride,
		        false, true, obj.UsageFlags, obj.Scale
		    )
		end
        alt_formatter = function(obj)

            return format_value(
                obj.Key, obj.Value, obj.Type, obj.LocTokenOverride,
                false, false, obj.UsageFlags, obj.Scale
            )
        end
    end

    ------------------------------------------------------------------
    -- Passive & Active stats (unified loop)
    ------------------------------------------------------------------
    local passive_counter, active_counter = 1, 1

    for _, section in ipairs(sections) do
        local stype = section.Type
        if stype ~= "Innate" then
            local is_active = (stype == "Active")
            local prefix = is_active and "active" or "passive"
            local counter = is_active and active_counter or passive_counter
            local stat_fmt = "| " .. prefix .. "%d_stat%d = %s"

            -- Description
            local loc = section.DescKey
            if loc then
                loc = loc:gsub("#", "")
                if loc ~= "" then
                    insert(lines, format(
                        "| %s%d_description = {{#invoke:Lang|get_string|%s|item_name=%s}}",
                        prefix, counter, loc, item_name
                    ))
                end
            end

            -- Stats
            local seen = {}
            local stat_index = process_stats(
                lines, stat_fmt, counter, 1,
                section.Main, item_name, seen, main_formatter
            )
            process_stats(
                lines, stat_fmt, counter, stat_index,
                section.Alt, item_name, seen, alt_formatter
            )

            -- Cooldown / ChargeUp
            local cd = format_section_cooldown(section, item_name, enhanced)
            if cd.cooldown then
                insert(lines, format("| %s%d_cooldown = %s", prefix, counter, cd.cooldown))
            end
            if cd.chargeup then
                insert(lines, format("| %s%d_chargeup = %s", prefix, counter, cd.chargeup))
            end

            if is_active then
                active_counter = active_counter + 1
            else
                passive_counter = passive_counter + 1
            end
        end
    end

    ------------------------------------------------------------------
    -- Components
    ------------------------------------------------------------------
    for i = 1, 2 do
        local comp = ItemData.get_component_name { args = { item_name, i } }
        if comp and comp ~= "" then
            insert(lines, format("| component%d_name = %s", i, comp))
        end
    end

    ------------------------------------------------------------------
    -- Is Component Of (sorted by tier)
    ------------------------------------------------------------------
    local parents = get_component_of_sorted(item_name)
    for i, key in ipairs(parents) do
        local d = data[key]
        local parent_name = d and d.Name or ""
        if parent_name ~= "" then
            insert(lines, format("| iscomponentof%d_name = %s", i, parent_name))
        end
    end

    ------------------------------------------------------------------
    -- Sounds (pass-through from frame args)
    ------------------------------------------------------------------
    for key, value in pairs(frame.args) do
        local index = tostring(key):match("^sound(%d+)$")
        if index and value ~= "" then
            insert(lines, format("| sound%s = %s", index, value))
        end
    end

    insert(lines, "}}")
    return concat(lines, "\n")
end
--------------------------------------------------------------------------------
-- Public interface
--------------------------------------------------------------------------------

-- Render only Default item infobox
function p.fill_tooltip(frame)
    local output = build_tooltip_impl(frame, false)
    local debug = tonumber(frame.args.debug) or 0
    if debug == 1 or debug == 2 then return output end
    return mw.getCurrentFrame():preprocess(output)
end

-- Render only Enhanced item infobox
function p.fill_tooltip_enhanced(frame)
    return mw.getCurrentFrame():preprocess(build_tooltip_impl(frame, true))
end

-- Render both Default and Enhanced item infobox using tabber
function p.render(frame)
    local output = concat({
        "<tabber>",
        lang.get_string("citadel_settings_camera_preset_default") .. "=",
        build_tooltip_impl(frame, false),
        "|-|",
        lang.get_string("Citadel_ItemDraft_Enhanced") .. "=",
        build_tooltip_impl(frame, true),
        "</tabber>"
    }, "\n")
    return mw.getCurrentFrame():preprocess(output)
end

return p