Module:Sandbox/LVL: Difference between revisions

From The Deadlock Wiki
Jump to navigation Jump to search
LVL (talk | contribs)
No edit summary
LVL (talk | contribs)
No edit summary
 
(91 intermediate revisions by the same user not shown)
Line 1: Line 1:
local p = {}
local p = {}
local lang = require "Module:Lang"
local util_module = require "Module:Utilities"
local data = mw.loadJsonData("Data:Monster_Domosed/ItemData.json")


-- Get raw value, CSS class, and LocTokenOverride for a property
local heroes_data      = mw.loadJsonData("Data:HeroData.json")
local function get_raw_value(item_name, prop)
local attributes_data  = mw.loadJsonData("Data:AttributeData.json")
    local item = data[item_name] or nil
local attribute_orders  = mw.loadJsonData("Data:StatInfoboxOrder.json")
    if not item then
local util_module      = require('Module:Utilities')
        for k,v in pairs(data) do
local lang_module      = require('Module:Lang')
            if v.Name == item_name then item = v; break end
local dictionary_module = require('Module:Dictionary')
        end
local attribute_module  = require('Module:AttributeData')
    end
local hero_data_module  = require('Module:HeroData')
    if not item then return nil, nil, nil end


    local raw_prop = item[prop]
local function get_nested_stat_value(hero_data, stat_key)
     if type(raw_prop) == "table" then
     if hero_data[stat_key] ~= nil then
         local loc_override = raw_prop.LocTokenOverride or prop
         return hero_data[stat_key]
         return raw_prop.Value, raw_prop.CSSClass, loc_override
    elseif hero_data.Weapon and hero_data.Weapon[stat_key] ~= nil then
     else
         return hero_data.Weapon[stat_key]
         return raw_prop, nil, prop
     elseif hero_data.Weapon and hero_data.Weapon.AltFire and hero_data.Weapon.AltFire[stat_key] ~= nil then
         return hero_data.Weapon.AltFire[stat_key]
     end
     end
    return 0
end
end


-- Check if property exists in language data
local function localize(key, fallback)
local function is_property_in_lang_data(prop)
     local result = lang_module.get_string(key)
     local keys = {
    if result == "" or result == nil then
        prop .. "_label",
         result = util_module.add_space_before_cap(fallback) ..
        prop .. "_Label",
                mw.getCurrentFrame():expandTemplate{title = "MissingValveTranslationTooltip"}
         prop .. "_prefix",
        prop .. "_Prefix",
        prop .. "_postfix",
        prop .. "_Postfix",
        prop .. "_postvalue_label",
        prop .. "_Postvalue_Label"
    }
 
    for _, key in ipairs(keys) do
        if lang.get_string(key) then
            return true
        end
     end
     end
    return result
end


    return false
-- =========================================================================
end
--  DPS calculation helpers
-- =========================================================================


-- Get item by name, ignoring disabled if possible
local function calculate_dps(stats, dps_type)
local function get_json_item(name)
     local rps = stats.RoundsPerSecond or 0
     for _, v in pairs(data) do
     if rps == 0 then return 0 end
        if v.Name == name and (v.IsDisabled == false or v.IsDisabled == nil) then
            return v
        end
     end
    for _, v in pairs(data) do
        if v.Name == name then return v end
    end
    return nil
end


-- Format stat value for Infobox, handling prefix/postfix, CSS, scaling, and conditional
    local bullets_per_shot = (stats.HitOnceAcrossAllBullets and 1) or (stats.BulletsPerShot or 1)
local function format_stat(item_name, prop, skip_label, debug, allow_conditional)
     local burst_count = stats.BulletsPerBurst or 1
     if allow_conditional == nil then allow_conditional = true end
    local cycle_time = 1 / rps
    local total_cycle_time = cycle_time * burst_count


     if prop == "AbilityCooldown" and not skip_label then
     if total_cycle_time == 0 then return 0 end
        return nil
    end


     local value, css, loc_key = get_raw_value(item_name, prop)
     local base_damage = stats.BulletDamage or 0
     if value == nil or value == 0 or value == "" then
     if dps_type == 'burst' then
    return nil
        return base_damage * bullets_per_shot * burst_count / total_cycle_time
     end
     end


    -- Convert string like "0m" or "0.0" to number for zero check
     local clip_size = stats.ClipSize or 0
     local numeric_val = tonumber(tostring(value):match("^-?%d+%.?%d*")) or 0
     if clip_size <= 0 then
     if numeric_val == 0 then
         return base_damage * bullets_per_shot * burst_count / total_cycle_time
         return nil
     end
     end


     -- Skip if property has no lang data
     local reload_time
     local label_key = loc_key:gsub("^#", "")
     if stats.ReloadSingle then
if not (
        reload_time = (stats.ReloadTime or 0) * clip_size
    lang.get_string(label_key.."_label") or
    else
    lang.get_string(label_key.."_Label") or
        reload_time = stats.ReloadTime or 0
    lang.get_string(label_key.."_prefix") or
    lang.get_string(label_key.."_Prefix") or
    lang.get_string(label_key.."_postfix") or
    lang.get_string(label_key.."_Postfix") or
    lang.get_string(label_key.."_postvalue_label") or
    lang.get_string(label_key.."_Postvalue_Label")
) then
    return nil
end
if debug == 2 then
    local label_val, prefix_val, postfix_val
    -- determine which label key worked
    if lang.get_string(label_key.."_label") then
        label_val = label_key.."_label"
    elseif lang.get_string(label_key.."_Label") then
        label_val = label_key.."_Label"
    else
        label_val = "(none)"
    end
    -- determine which prefix key worked
    if lang.get_string(label_key.."_prefix") then
        prefix_val = label_key.."_prefix"
    elseif lang.get_string(label_key.."_Prefix") then
        prefix_val = label_key.."_Prefix"
    else
        prefix_val = "(none)"
    end
    -- determine which postfix key worked
    if lang.get_string(label_key.."_postfix") then
        postfix_val = label_key.."_postfix"
    elseif lang.get_string(label_key.."_Postfix") then
        postfix_val = label_key.."_Postfix"
    else
        postfix_val = "(none)"
    end
    return string.format(
        "raw invoke key: %s | raw value: %s | label key used: %s | prefix key used: %s | postfix key used: %s",
        loc_key,
        tostring(value),
        label_val,
        prefix_val,
        postfix_val
    )
end
 
    if prop == "BuildUpPerShot" then label_key = "BuildupPerShot"
    elseif prop == "DotDuration" then label_key = "DOTDuration"
     end
     end
    reload_time = reload_time + (stats.ReloadDelay or 0)


-- Helper function: get first non-nil string from variants
    local time_to_empty_clip = (clip_size / burst_count) * total_cycle_time
local function first_non_nil(...)
     local damage_from_clip = base_damage * bullets_per_shot * clip_size
     for i = 1, select("#", ...) do
    local total_time = time_to_empty_clip + reload_time
        local v = select(i, ...)
    if total_time == 0 then return 0 end
        if v and v ~= "" then return v end
     return damage_from_clip / total_time
    end
     return ""
end
end


-- Get actual label, prefix, postfix with fallbacks
-- Compute how much DPS changes when all relevant component scalings are applied.
local label = skip_label and "" or first_non_nil(
-- Used for alt-fire rows where explicit DPS/SustainedDPS scaling keys are missing.
    lang.get_string(label_key.."_label"),
local function compute_dps_scaling(hero_data, base_stats, dps_type, scaling_type)
     lang.get_string(label_key.."_Label")
     local scaling_source = hero_data[scaling_type .. "Scaling"] or {}
)


local prefix = first_non_nil(
    local component_scalings = {}
     lang.get_string(label_key.."_prefix"),
     local possible_keys = {
    lang.get_string(label_key.."_Prefix")
        "BulletDamage", "RoundsPerSecond", "ClipSize", "ReloadTime",
)
        "ReloadDelay", "BulletsPerShot", "BulletsPerBurst"
 
    }
local postfix = first_non_nil(
     for _, key in ipairs(possible_keys) do
    lang.get_string(label_key.."_postfix"),
         local alt_key = key .. "AltFire"
    lang.get_string(label_key.."_Postfix")
         if scaling_source[alt_key] then
)
             component_scalings[key] = scaling_source[alt_key]
   
    if prefix == "" and postfix == "" and label == "" then
    return nil
end
 
     local val_str = tostring(value)
 
    ------------------------------------------------------------------
    -- CSS-specific formatting
    ------------------------------------------------------------------
    if css == "move_speed" or css == "sprint_speed" then
         if postfix == "" or not postfix:find("%%") then
            val_str = val_str:gsub("/s", "") .. "/s"
        end
        local num = tonumber(val_str:match("^-?%d+%.?%d*"))
         if num and num > 0 and not val_str:find("^%+") then
             val_str = "+" .. val_str
         end
         end
     end
     end


     ------------------------------------------------------------------
     -- ClipSize is shared between fire modes; fall back to primary scaling
    -- Apply prefix
     if base_stats.ClipSize and not component_scalings.ClipSize then
    ------------------------------------------------------------------
         local primary_clip_scale = scaling_source["ClipSize"]
     if prefix ~= "" then
        if primary_clip_scale then
         if prefix == "{s:sign}" then
            component_scalings.ClipSize = primary_clip_scale
            local num = tonumber(val_str:match("^-?%d+%.?%d*"))
            if num and num >= 0 and not val_str:find("^%+") then
                val_str = "+"..val_str
            end
        else
            val_str = prefix..val_str
         end
         end
     end
     end


     ------------------------------------------------------------------
     if next(component_scalings) == nil then
    -- Append postfix
        return 0
    ------------------------------------------------------------------
-- Append postfix
if prop ~= "BuildUpPerShot" and postfix ~= "" and not val_str:find(postfix, 1, true) then
    if postfix == "HP/s" then
        val_str = val_str .. " " .. postfix
    else
        val_str = val_str .. postfix
    end
end
 
    ------------------------------------------------------------------
    -- Append scaling template {{Boon}} or {{Ss}}
    ------------------------------------------------------------------
    local item = get_json_item(item_name)
    local raw_prop = item[prop]
    if type(raw_prop) == "table" and raw_prop.Scale and raw_prop.Scale.Value ~= 0 then
        local scale_val = util_module.round_to_sig_fig(raw_prop.Scale.Value, 2)
        local template_name = (raw_prop.Scale.Type == "power_increase") and "Boon" or "Ss"
        val_str = val_str .. " " .. mw.getCurrentFrame():expandTemplate{ title = template_name, args = { scale_val } }
     end
     end


     ------------------------------------------------------------------
     local base_dps = calculate_dps(base_stats, dps_type)
     -- Append label
     local scaled_stats = {}
     ------------------------------------------------------------------
     for k, v in pairs(base_stats) do scaled_stats[k] = v end
     if label ~= "" then
     for comp_key, scale_val in pairs(component_scalings) do
         val_str = val_str.." "..label
        if scaled_stats[comp_key] ~= nil then
            scaled_stats[comp_key] = scaled_stats[comp_key] + scale_val
         end
     end
     end
    local scaled_dps = calculate_dps(scaled_stats, dps_type)
    return scaled_dps - base_dps
end


    ------------------------------------------------------------------
-- =========================================================================
    -- Append (Conditional) ONLY if allowed
-- Main module function
    ------------------------------------------------------------------
-- =========================================================================
if allow_conditional
    and type(raw_prop) == "table"
    and (raw_prop.UsageFlags == "ConditionallyApplied" or raw_prop.UsageFlags == "ConditionallyEnemyApplied")
then
    local conditional_text = lang.get_string("Citadel_Shop_ConditionalAttribute")
    val_str = val_str .. string.format(' <span style="color:#C0C0C0">(%s)</span>', conditional_text)
end


    return val_str
p.write_hero_comparison_table = function(frame)
end
     local power_increases = tonumber(frame.args[1]) or 0
 
    local spirit_power    = tonumber(frame.args[2]) or 0
-- Special formatting for StatusEffect
    local max_power      = tonumber(frame.args[3]) or 25
local function format_property_for_infobox(item_name, prop, skip_label, debug)
     local max_spirit      = tonumber(frame.args[4]) or 500
     if prop:match("^StatusEffect") then
        return string.format(
            "[[{{#invoke:Lang|get_string|Citadel_%s}}]] [[{{#invoke:Lang|get_string|Citadel_StatusEffect}}]]",
            prop
        )
     else
        return format_stat(item_name, prop, skip_label, debug, true)
    end
end


function p.fill_tooltip(frame)
     local display_scaling_icons = (power_increases == 0 and spirit_power == 0)
     local item_name = frame.args[1]
    if not item_name then return "Item name missing" end


     local debug = tonumber(frame.args.debug) or 0
     local body_str = ""
    local item = get_json_item(item_name)
    if not item then return "Item not found" end


     local ItemData = require("Module:ItemData")
     local stats_to_include = {
    local lines = {
        Weapon = {
        "{{Infobox item",
            "DPS", "SustainedDPS", "BulletDamage", "RoundsPerSecond", "FireRate",
         "| item_name = " .. item_name
            "ClipSize", "ReloadTime", "ReloadDelay", "ReloadSingle", "BulletsPerShot", "BulletsPerBurst",
            "BurstInterShotInterval", "LightMeleeDamage", "HeavyMeleeDamage",
            "BulletSpeed", "FalloffStartRange", "FalloffEndRange",
            "CritDamageBonusPercent", "BulletRadius", "RoundsPerSecondAtMaxSpin", "SpinAcceleration", "SpinDeceleration"
        },
        Vitality = {
            "MaxHealth", "BaseHealthRegen", "BulletResist", "TechResist", "MeleeResist",
            "CritDamageReceivedPercent", "DebuffResist", "BulletLifesteal", "MaxMoveSpeed",
            "SprintSpeed", "StaminaCooldown", "Stamina", "GroundDashSpeed", "GravityChange"
        },
         Spirit = { "TechPower" }
     }
     }


     ----------------------------------------------------------------------
     -- Collect and sort heroes alphabetically, excluding disabled/in-development
    -- Check if AbilityCooldown or AbilityChargeUpTime exists in sections
     local sorted_heroes = {}
    ----------------------------------------------------------------------
     for hero_key, hero_data in pairs(heroes_data) do
     local cooldown_found_in_sections = false
         if not hero_data["InDevelopment"] and not hero_data["IsDisabled"] then
    local chargeup_found_in_sections = false
             table.insert(sorted_heroes, {key = hero_key, data = hero_data})
     for _, section in ipairs(item.TooltipSections or {}) do
         for _, entry in ipairs(section.Entries or {}) do
            for _, prop in ipairs(entry.Properties or {}) do
                if prop == "AbilityCooldown" then cooldown_found_in_sections = true end
                if prop == "AbilityChargeUpTime" then chargeup_found_in_sections = true end
             end
            for _, prop in ipairs(entry.ImportantProperties or {}) do
                if prop == "AbilityCooldown" then cooldown_found_in_sections = true end
                if prop == "AbilityChargeUpTime" then chargeup_found_in_sections = true end
            end
         end
         end
     end
     end
    table.sort(sorted_heroes, function(a, b)
        local function get_sort_name(name)
            return (name:gsub("^The ", ""))
        end
        return get_sort_name(a.data["Name"] or a.key) < get_sort_name(b.data["Name"] or b.key)
    end)
    -- Build a single stat cell (<td>) with data attributes for JS recalculation
    local function buildStatCell(hero_data, hero_key, attr_key, is_alt_fire, category)
        -- Conversion factors for stats that need unit changes (e.g. metres → centimetres)
        local unit_conversion = {
            BulletRadius = 100  -- metres to centimetres
        }
        local conv_factor = unit_conversion[attr_key] or 1


    ----------------------------------------------------------------------
        local base_value
    -- Innate stats
         if is_alt_fire then
    ----------------------------------------------------------------------
             if attr_key == "ClipSize" or attr_key == "ReloadTime" then
    local innate_index = 1
                base_value = get_nested_stat_value(hero_data, attr_key)
    for _, section in ipairs(item.TooltipSections or {}) do
            elseif hero_data.Weapon and hero_data.Weapon.AltFire
         if section.Type == "EArea_Innate" then
                and hero_data.Weapon.AltFire[attr_key] ~= nil then
             for _, entry in ipairs(section.Entries or {}) do
                base_value = hero_data.Weapon.AltFire[attr_key]
                for _, prop in ipairs(entry.Properties or {}) do
            else
                    if prop ~= "AbilityCooldown" and prop ~= "AbilityChargeUpTime" then
                 base_value = get_nested_stat_value(hero_data, attr_key)
                        local val = format_stat(item_name, prop, false, debug, false)
                        if val then
                            table.insert(lines, string.format("| item_stat%d = %s", innate_index, val))
                            innate_index = innate_index + 1
                        end
                    end
                 end
             end
             end
        else
            base_value = get_nested_stat_value(hero_data, attr_key)
         end
         end
    end


    ----------------------------------------------------------------------
        -- Apply unit conversion to the base value
    -- Passive stats
        if type(base_value) == "number" then
    ----------------------------------------------------------------------
             base_value = base_value * conv_factor
    local passive_counter = 1
        end
    for _, section in ipairs(item.TooltipSections or {}) do
        if section.Type ~= "EArea_Innate" and section.Type ~= "EArea_Active" then
             for _, entry in ipairs(section.Entries or {}) do
                local loc = entry.LocString and entry.LocString:gsub("#","") or nil
                if loc then
                    table.insert(
                        lines,
                        string.format(
                            "| passive%d_description = {{#invoke:Lang|get_string|%s|item_name=%s}}",
                            passive_counter, loc, item_name
                        )
                    )
                end


                local stat_index = 1
        local stat_value = base_value
                local seen_props = {}


                -- ImportantProperties
        -- Scaling lookup
                 for _, prop in ipairs(entry.ImportantProperties or {}) do
        local scaling_data
                    if prop ~= "AbilityCooldown" and prop ~= "AbilityChargeUpTime" and is_property_in_lang_data(prop) and not seen_props[prop] then
        if is_alt_fire then
                        local val = format_property_for_infobox(item_name, prop, false, debug)
            if attr_key == "ClipSize" or attr_key == "ReloadTime" then
                        if val then
                 scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
                            table.insert(lines, string.format("| passive%d_stat%d = %s", passive_counter, stat_index, val))
            elseif (attr_key == "DPS" or attr_key == "SustainedDPS")
                            stat_index = stat_index + 1
                and hero_data.Weapon and hero_data.Weapon.AltFire then
                            seen_props[prop] = true
                -- Alt-fire DPS/SustainedDPS: use explicit key if present, otherwise compute from components
                        end
                local direct_scaling = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
                     end
                if direct_scaling and next(direct_scaling) ~= nil then
                    scaling_data = direct_scaling
                else
                    local alt_stats = hero_data.Weapon.AltFire
                    local dps_type = attr_key == "DPS" and 'burst' or 'sustained'
                    local level_scale = compute_dps_scaling(hero_data, alt_stats, dps_type, "Level")
                    local spirit_scale = compute_dps_scaling(hero_data, alt_stats, dps_type, "Spirit")
                    level_scale = util_module.round_to_sig_fig(level_scale, 5)
                    spirit_scale = util_module.round_to_sig_fig(spirit_scale, 5)
                    scaling_data = {}
                    if level_scale ~= 0 then scaling_data[level_scale] = "Level" end
                    if spirit_scale ~= 0 then scaling_data[spirit_scale] = "Spirit" end
                     if next(scaling_data) == nil then scaling_data = nil end
                 end
                 end
            elseif hero_data.Weapon and hero_data.Weapon.AltFire
                and hero_data.Weapon.AltFire[attr_key] ~= nil then
                scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
            else
                scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
            end
        else
            scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
        end


                -- Properties
        local scaling_strs = ""
                for _, prop in ipairs(entry.Properties or {}) do
        local spirit_scale = 0
                    if prop ~= "AbilityCooldown" and prop ~= "AbilityChargeUpTime" and is_property_in_lang_data(prop) and not seen_props[prop] then
        local level_scale  = 0
                        local val = format_property_for_infobox(item_name, prop, false, debug)
        local spirit_val = 0
                        if val then
        local level_val  = 0
                            table.insert(lines, string.format("| passive%d_stat%d = %s", passive_counter, stat_index, val))
        if scaling_data ~= nil then
                            stat_index = stat_index + 1
            for scaling_val, scaling_type in pairs(scaling_data) do
                            seen_props[prop] = true
                if scaling_type == "Spirit" then
                        end
                    spirit_val = scaling_val * conv_factor  -- apply unit conversion
                    end
                elseif scaling_type == "Level" then
                    level_val = scaling_val * conv_factor  -- apply unit conversion
                 end
                 end
            end


                -- AbilityCooldown
            -- Output Spirit icon before Level icon
                for _, prop in ipairs(entry.Properties or {}) do
            local function append_scaling(val, stype)
                    if prop == "AbilityCooldown" then
                if val ~= 0 then
                        local cd = format_stat(item_name, prop, true, debug)
                    local scaling_str = hero_data_module.write_scalar_str(val, stype, true)
                        if cd then
                     if scaling_str ~= "" then
                            table.insert(lines, string.format("| passive%d_cooldown = %s", passive_counter, cd))
                         scaling_strs = scaling_strs .. " " .. scaling_str
                        end
                    end
                end
                for _, prop in ipairs(entry.ImportantProperties or {}) do
                     if prop == "AbilityCooldown" then
                         local cd = format_stat(item_name, prop, true, debug)
                        if cd then
                            table.insert(lines, string.format("| passive%d_cooldown = %s", passive_counter, cd))
                        end
                     end
                     end
                 end
                 end
            end
            append_scaling(spirit_val, "Spirit")
            append_scaling(level_val, "Level")
            if type(stat_value) == "number" then
                stat_value = stat_value + (spirit_power * spirit_val)
                stat_value = stat_value + (power_increases * level_val)
            end


                -- AbilityChargeUpTime
            spirit_scale = spirit_val
                for _, prop in ipairs(entry.Properties or {}) do
            level_scale  = level_val
                    if prop == "AbilityChargeUpTime" then
        end
                        local cu = format_stat(item_name, prop, true, debug)
                        if cu then
                            table.insert(lines, string.format("| passive%d_chargeup = %s", passive_counter, cu))
                        end
                    end
                end
                for _, prop in ipairs(entry.ImportantProperties or {}) do
                    if prop == "AbilityChargeUpTime" then
                        local cu = format_stat(item_name, prop, true, debug)
                        if cu then
                            table.insert(lines, string.format("| passive%d_chargeup = %s", passive_counter, cu))
                        end
                    end
                end


                 passive_counter = passive_counter + 1
        if attr_key == "TechPower" and spirit_scale == 0 then
            spirit_scale = 1.0
            if type(stat_value) == "number" then
                 stat_value = stat_value + (spirit_power * spirit_scale)
             end
             end
         end
         end
    end


    ----------------------------------------------------------------------
        local innate_spirit_scale =
    -- Active stats
             (hero_data["LevelScaling"] and hero_data["LevelScaling"]["TechPower"]) or 0
    ----------------------------------------------------------------------
    local active_index = 1
    for _, section in ipairs(item.TooltipSections or {}) do
        if section.Type == "EArea_Active" then
             for _, entry in ipairs(section.Entries or {}) do
                if entry.LocString then
                    table.insert(
                        lines,
                        string.format(
                            "| active%d_description = {{#invoke:Lang|get_string|%s|item_name=%s}}",
                            active_index,
                            entry.LocString:gsub("#",""),
                            item_name
                        )
                    )
                end


                local stat_index = 1
        if not display_scaling_icons then scaling_strs = "" end
                local seen_props = {}


                -- ImportantProperties
        if type(stat_value) == "boolean" then
                for _, prop in ipairs(entry.ImportantProperties or {}) do
            stat_value = tostring(stat_value)
                    if prop ~= "AbilityCooldown" and prop ~= "AbilityChargeUpTime" and is_property_in_lang_data(prop) and not seen_props[prop] then
        else
                        local val = format_property_for_infobox(item_name, prop, false, debug)
            stat_value = util_module.round_to_sig_fig(stat_value, 5)
                        if val then
        end
                            table.insert(lines, string.format("| active%d_stat%d = %s", active_index, stat_index, val))
                            stat_index = stat_index + 1
                            seen_props[prop] = true
                        end
                    end
                end


                -- Properties
        local cell_inner = string.format(
                for _, prop in ipairs(entry.Properties or {}) do
            '<span class="stat-num">%s</span><span class="stat-scaling">%s</span>',
                    if prop ~= "AbilityCooldown" and prop ~= "AbilityChargeUpTime" and is_property_in_lang_data(prop) and not seen_props[prop] then
            stat_value,
                        local val = format_property_for_infobox(item_name, prop, false, debug)
            scaling_strs
                        if val then
        )
                            table.insert(lines, string.format("| active%d_stat%d = %s", active_index, stat_index, val))
                            stat_index = stat_index + 1
                            seen_props[prop] = true
                        end
                    end
                end


                -- AbilityCooldown
        local weapon_table = hero_data.Weapon
                for _, prop in ipairs(entry.Properties or {}) do
        if is_alt_fire and weapon_table and weapon_table.AltFire then
                    if prop == "AbilityCooldown" then
            weapon_table = weapon_table.AltFire
                        local cd = format_stat(item_name, prop, true, debug)
        end
                        if cd then
        local hit_once = "false"
                            table.insert(lines, string.format("| active%d_cooldown = %s", active_index, cd))
        if (attr_key == "DPS" or attr_key == "SustainedDPS")
                        end
            and weapon_table
                    end
            and weapon_table.HitOnceAcrossAllBullets
                end
        then
                for _, prop in ipairs(entry.ImportantProperties or {}) do
            hit_once = "true"
                    if prop == "AbilityCooldown" then
        end
                        local cd = format_stat(item_name, prop, true, debug)
                        if cd then
                            table.insert(lines, string.format("| active%d_cooldown = %s", active_index, cd))
                        end
                    end
                end


                -- AbilityChargeUpTime
        local data_attrs = string.format(
                for _, prop in ipairs(entry.Properties or {}) do
            'data-stat-name="%s" data-base="%s" data-spirit-scale="%s" data-level-scale="%s" data-innate-spirit-scale="%s" data-sort-value="%s" data-hit-once="%s"',
                    if prop == "AbilityChargeUpTime" then
            attr_key,
                        local cu = format_stat(item_name, prop, true, debug)
            tostring(type(base_value) == "number" and util_module.round_to_sig_fig(base_value, 3) or base_value),
                        if cu then
            tonumber(spirit_scale) or 0,
                            table.insert(lines, string.format("| active%d_chargeup = %s", active_index, cu))
            (attr_key == "TechPower") and "0" or (tonumber(level_scale) or 0),
                        end
            innate_spirit_scale or 0,
                    end
            stat_value,
                end
            hit_once
                for _, prop in ipairs(entry.ImportantProperties or {}) do
        )
                    if prop == "AbilityChargeUpTime" then
                        local cu = format_stat(item_name, prop, true, debug)
                        if cu then
                            table.insert(lines, string.format("| active%d_chargeup = %s", active_index, cu))
                        end
                    end
                end


                active_index = active_index + 1
        return string.format('<td style="white-space: nowrap;" %s>%s</td>', data_attrs, cell_inner)
            end
        end
     end
     end


     ----------------------------------------------------------------------
     -- Generate a hero's primary stat row
     -- Global fallback for AbilityCooldown and AbilityChargeUpTime
     local function generatePrimaryRow(hero_data, hero_key, has_alt)
    ----------------------------------------------------------------------
        local row_str = ""
    if not cooldown_found_in_sections and item.AbilityCooldown then
        local hero_name_local = localize(hero_key, hero_key)
         local cd = format_stat(item_name, "AbilityCooldown", true, debug)
        local hero_name_en = hero_data["Name"]
        if cd then
        local template_args = {[1] = hero_name_en, l1 = hero_name_local}
            table.insert(lines, "| item_stat_cooldown = " .. cd)
        local hero_icon = mw.getCurrentFrame():expandTemplate{ title = "Template:HeroIcon", args = template_args }
        local hero_cell_content = hero_icon
        if has_alt then
            hero_cell_content = '[[#alt-fire-' .. hero_key .. '|+]] ' .. hero_cell_content
        end
        local sort_name = (hero_data["Name"] or hero_key):gsub("^The ", "")
        row_str = row_str .. '<td style="position: sticky; left: 0; z-index: 10; background-color: var(--background-color-base-2); isolation: isolate; overflow: hidden; min-width: 150px;" data-sort-value="' .. sort_name .. '">' .. hero_cell_content .. '</td>'
         for _, category in ipairs(attribute_orders["category_order"]) do
            if stats_to_include[category] ~= nil then
                for _, attr_key in ipairs(stats_to_include[category]) do
                    row_str = row_str .. buildStatCell(hero_data, hero_key, attr_key, false, category)
                end
            end
         end
         end
        return "<tr>" .. row_str .. "</tr>"
     end
     end


     if not chargeup_found_in_sections and item.AbilityChargeUpTime then
     -- Generate an expandable alt-fire sub-row (weapon stats only)
         local cu = format_stat(item_name, "AbilityChargeUpTime", true, debug)
    local function generateAltFireSubRow(hero_data, hero_key)
        if cu then
        local row_str = ""
            table.insert(lines, "| item_stat_chargeup = " .. cu)
        local hero_name_local = localize(hero_key, hero_key)
        local hero_name_en = hero_data["Name"]
        local template_args = {[1] = hero_name_en, l1 = hero_name_local}
        local hero_icon = mw.getCurrentFrame():expandTemplate{ title = "Template:HeroIcon", args = template_args }
        local hero_cell_content = hero_icon .. ' <small style="color:#aaa;">(Alt‑fire)</small>'
         local sort_name = (hero_data["Name"] or hero_key):gsub("^The ", "")
        row_str = row_str .. '<td style="position: sticky; left: 0; z-index: 9; background-color: #202122; isolation: isolate; overflow: hidden; min-width: 150px;" data-sort-value="' .. sort_name .. '">' .. hero_cell_content .. '</td>'
        for _, category in ipairs(attribute_orders["category_order"]) do
            if stats_to_include[category] ~= nil then
                for _, attr_key in ipairs(stats_to_include[category]) do
                    if category == "Weapon" then
                        row_str = row_str .. buildStatCell(hero_data, hero_key, attr_key, true, category)
                    else
                        row_str = row_str .. '<td></td>'
                    end
                end
            end
         end
         end
        return '<tr class="alt-fire-sub" data-parent="' .. hero_key .. '">' .. row_str .. '</tr>'
     end
     end


     ----------------------------------------------------------------------
     -- Build all body rows
    -- Components
     for _, hero_entry in ipairs(sorted_heroes) do
    ----------------------------------------------------------------------
         local hero_key  = hero_entry.key
     for i = 1, 2 do
        local hero_data = hero_entry.data
         local comp = ItemData.get_component_name {
        local has_alt = hero_data.Weapon and hero_data.Weapon.AltFire and true or false
            args = { item_name, i }
         body_str = body_str .. generatePrimaryRow(hero_data, hero_key, has_alt)
         }
         if has_alt then
         if comp and comp ~= "" then
             body_str = body_str .. generateAltFireSubRow(hero_data, hero_key)
             table.insert(lines, string.format("| component%d_name = %s", i, comp))
         end
         end
     end
     end


     ----------------------------------------------------------------------
     -- Pre-pass: determine which stats have any scaling, and which have both types.
     -- Is Component Of
    -- Used to set column widths in the header.
     ----------------------------------------------------------------------
     local stats_with_any_scaling  = {}
     for i = 1, 3 do
     local stats_with_both_scaling = {}
         local parent = ItemData.get_builds_into_name {
     for _, hero_entry in ipairs(sorted_heroes) do
             args = { item_name, i }
         local hero_data = hero_entry.data
        }
        for _, category in ipairs(attribute_orders["category_order"]) do
        if parent and parent ~= "" then
             if stats_to_include[category] ~= nil then
            table.insert(lines, string.format("| iscomponentof%d_name = %s", i, parent))
                for _, attr_key in ipairs(stats_to_include[category]) do
        end
                    -- Primary scaling
    end
                    local scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
                    if scaling_data ~= nil and next(scaling_data) ~= nil then
                        stats_with_any_scaling[attr_key] = true
                        local has_spirit, has_level = false, false
                        for _, scaling_type in pairs(scaling_data) do
                            if scaling_type == "Spirit" then has_spirit = true
                            elseif scaling_type == "Level" then has_level = true end
                        end
                        if has_spirit and has_level then stats_with_both_scaling[attr_key] = true end
                    end


    ----------------------------------------------------------------------
                    -- Alt-fire scaling (only for stats present in the AltFire table)
    -- Sounds (sound1, sound2, sound3, ...)
                    if hero_data.Weapon
    ----------------------------------------------------------------------
                        and hero_data.Weapon.AltFire
    for key, value in pairs(frame.args) do
                        and hero_data.Weapon.AltFire[attr_key] ~= nil
        local index = tostring(key):match("^sound(%d+)$")
                    then
        if index and value ~= "" then
                        if attr_key ~= "ClipSize" then
            table.insert(lines, string.format("| sound%s = %s", index, value))
                            local alt_scaling = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
                            if alt_scaling and next(alt_scaling) ~= nil then
                                stats_with_any_scaling[attr_key] = true
                                local has_spirit_alt, has_level_alt = false, false
                                for _, stype in pairs(alt_scaling) do
                                    if stype == "Spirit" then has_spirit_alt = true
                                    elseif stype == "Level" then has_level_alt = true end
                                end
                                if has_spirit_alt and has_level_alt then stats_with_both_scaling[attr_key] = true end
                            else
                                if attr_key == "DPS" or attr_key == "SustainedDPS" then
                                    local alt_stats = hero_data.Weapon.AltFire
                                    local dps_type = attr_key == "DPS" and 'burst' or 'sustained'
                                    local lv = compute_dps_scaling(hero_data, alt_stats, dps_type, "Level")
                                    local sp = compute_dps_scaling(hero_data, alt_stats, dps_type, "Spirit")
                                    lv = util_module.round_to_sig_fig(lv, 5)
                                    sp = util_module.round_to_sig_fig(sp, 5)
                                    if lv ~= 0 or sp ~= 0 then
                                        stats_with_any_scaling[attr_key] = true
                                        if lv ~= 0 and sp ~= 0 then
                                            stats_with_both_scaling[attr_key] = true
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
         end
         end
     end
     end


     ----------------------------------------------------------------------
     -- Build table header row
     table.insert(lines, "}}")
    local headers_str = '<th style="position: sticky; left: 0; top: -1px; z-index: 12; background-color: var(--background-color-base-5); isolation: isolate; min-width: 150px;">Hero</th>'
    local output = table.concat(lines, "\n")
     local category_data = attribute_module.get_category_data()
    local postfix_key_map = {
        ["ReloadDelay"] = "StatDesc_ReloadTime_postfix",
        ["BulletsPerShot"] = "",
        ["BulletsPerBurst"] = "",
        ["BurstInterShotInterval"] = "StatDesc_ReloadTime_postfix",
        ["ReloadSingle"] = "",
        ["BonusAttackRange"] = "StatDesc_WeaponRangeFalloffMax_postfix",
        ["SustainedDPS"] = "DPS_postfix",
        ["RoundsPerSecondAtMaxSpin"] = "",
        ["CritDamageBonusPercent"]  = "StatDesc_CritDamageBonusScale_postfix",
["CritDamageReceivedPercent"] = "StatDesc_CritDamageReceivedScale_postfix",
        ["BulletLifesteal"] = "BulletLifestealPercentHero_postfix",
        ["GroundDashSpeed"] = "DashSpeed_postfix"
    }
    for _, category in ipairs(attribute_orders["category_order"]) do
        local category_attrs = attributes_data[category]
        local category_rgb  = category_data[category]["rgb"]
        if stats_to_include[category] ~= nil then
            for _, attr_key in ipairs(stats_to_include[category]) do
                local attr_data = category_attrs[attr_key]
               
                -- Fallback: if the stat is missing from this category, check all other categories
                if attr_data == nil then
                    for _, fallback_cat_data in pairs(attributes_data) do
                        if fallback_cat_data[attr_key] ~= nil then
                            attr_data = fallback_cat_data[attr_key]
                            break
                        end
                    end
                end


    if debug == 1 or debug == 2 then
                local attr_localized, postfix
         return output
                if attr_data ~= nil then
                    attr_localized = lang_module.get_string(attr_data["label"])
                    if attr_localized == nil or attr_localized == "" then
                        attr_localized = util_module.add_space_before_cap(attr_key)
                    end
                    postfix = lang_module.get_string(attr_data["postfix"])
                    if postfix == nil or postfix == "" then postfix = ""
                    else postfix = " (" .. postfix .. ")" end
                    if attr_key == "BulletRadius" then postfix = " (cm)" end
                else
                    attr_localized = dictionary_module.translate(attr_key)
                    postfix = lang_module.get_string(postfix_key_map[attr_key])
                    if postfix == nil then return "attr_key " .. attr_key .. " must be added to postfix_key_map" end
                    if postfix ~= "" then postfix = " (" .. postfix .. ")" end
                end
                local th_style = 'position: sticky; top: -1px; z-index: 3; background-color: rgb(' .. category_rgb .. ');'
                if stats_with_both_scaling[attr_key] then
                    th_style = th_style .. ' min-width: 130px;'
                elseif stats_with_any_scaling[attr_key] then
                    th_style = th_style .. ' min-width: 75px;'
                end
                headers_str = headers_str .. '<th style="' .. th_style .. '">' .. attr_localized .. postfix .. "</th>"
            end
         end
     end
     end
    headers_str = "<tr>" .. headers_str .. "</tr>"


     return mw.getCurrentFrame():preprocess(output)
     return string.format(
        '<div id="hero-comparison-container" data-max-power="%s" data-max-spirit="%s">' ..
        '<div style="overflow: auto; max-height: 70vh; width: 100%%;">' ..
        '<table class="wikitable sortable" style="table-layout: auto; width: 100%%;" id="hero-comparison-table">%s%s</table>' ..
        '</div></div>',
        max_power, max_spirit, headers_str, body_str
    )
end
end


return p
return p

Latest revision as of 17:07, 14 August 2026

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

local p = {}

local heroes_data       = mw.loadJsonData("Data:HeroData.json")
local attributes_data   = mw.loadJsonData("Data:AttributeData.json")
local attribute_orders  = mw.loadJsonData("Data:StatInfoboxOrder.json")
local util_module       = require('Module:Utilities')
local lang_module       = require('Module:Lang')
local dictionary_module = require('Module:Dictionary')
local attribute_module  = require('Module:AttributeData')
local hero_data_module  = require('Module:HeroData')

local function get_nested_stat_value(hero_data, stat_key)
    if hero_data[stat_key] ~= nil then
        return hero_data[stat_key]
    elseif hero_data.Weapon and hero_data.Weapon[stat_key] ~= nil then
        return hero_data.Weapon[stat_key]
    elseif hero_data.Weapon and hero_data.Weapon.AltFire and hero_data.Weapon.AltFire[stat_key] ~= nil then
        return hero_data.Weapon.AltFire[stat_key]
    end
    return 0
end

local function localize(key, fallback)
    local result = lang_module.get_string(key)
    if result == "" or result == nil then
        result = util_module.add_space_before_cap(fallback) ..
                 mw.getCurrentFrame():expandTemplate{title = "MissingValveTranslationTooltip"}
    end
    return result
end

-- =========================================================================
--  DPS calculation helpers
-- =========================================================================

local function calculate_dps(stats, dps_type)
    local rps = stats.RoundsPerSecond or 0
    if rps == 0 then return 0 end

    local bullets_per_shot = (stats.HitOnceAcrossAllBullets and 1) or (stats.BulletsPerShot or 1)
    local burst_count = stats.BulletsPerBurst or 1
    local cycle_time = 1 / rps
    local total_cycle_time = cycle_time * burst_count

    if total_cycle_time == 0 then return 0 end

    local base_damage = stats.BulletDamage or 0
    if dps_type == 'burst' then
        return base_damage * bullets_per_shot * burst_count / total_cycle_time
    end

    local clip_size = stats.ClipSize or 0
    if clip_size <= 0 then
        return base_damage * bullets_per_shot * burst_count / total_cycle_time
    end

    local reload_time
    if stats.ReloadSingle then
        reload_time = (stats.ReloadTime or 0) * clip_size
    else
        reload_time = stats.ReloadTime or 0
    end
    reload_time = reload_time + (stats.ReloadDelay or 0)

    local time_to_empty_clip = (clip_size / burst_count) * total_cycle_time
    local damage_from_clip = base_damage * bullets_per_shot * clip_size
    local total_time = time_to_empty_clip + reload_time
    if total_time == 0 then return 0 end
    return damage_from_clip / total_time
end

-- Compute how much DPS changes when all relevant component scalings are applied.
-- Used for alt-fire rows where explicit DPS/SustainedDPS scaling keys are missing.
local function compute_dps_scaling(hero_data, base_stats, dps_type, scaling_type)
    local scaling_source = hero_data[scaling_type .. "Scaling"] or {}

    local component_scalings = {}
    local possible_keys = {
        "BulletDamage", "RoundsPerSecond", "ClipSize", "ReloadTime",
        "ReloadDelay", "BulletsPerShot", "BulletsPerBurst"
    }
    for _, key in ipairs(possible_keys) do
        local alt_key = key .. "AltFire"
        if scaling_source[alt_key] then
            component_scalings[key] = scaling_source[alt_key]
        end
    end

    -- ClipSize is shared between fire modes; fall back to primary scaling
    if base_stats.ClipSize and not component_scalings.ClipSize then
        local primary_clip_scale = scaling_source["ClipSize"]
        if primary_clip_scale then
            component_scalings.ClipSize = primary_clip_scale
        end
    end

    if next(component_scalings) == nil then
        return 0
    end

    local base_dps = calculate_dps(base_stats, dps_type)
    local scaled_stats = {}
    for k, v in pairs(base_stats) do scaled_stats[k] = v end
    for comp_key, scale_val in pairs(component_scalings) do
        if scaled_stats[comp_key] ~= nil then
            scaled_stats[comp_key] = scaled_stats[comp_key] + scale_val
        end
    end
    local scaled_dps = calculate_dps(scaled_stats, dps_type)
    return scaled_dps - base_dps
end

-- =========================================================================
--  Main module function
-- =========================================================================

p.write_hero_comparison_table = function(frame)
    local power_increases = tonumber(frame.args[1]) or 0
    local spirit_power    = tonumber(frame.args[2]) or 0
    local max_power       = tonumber(frame.args[3]) or 25
    local max_spirit      = tonumber(frame.args[4]) or 500

    local display_scaling_icons = (power_increases == 0 and spirit_power == 0)

    local body_str = ""

    local stats_to_include = {
        Weapon = {
            "DPS", "SustainedDPS", "BulletDamage", "RoundsPerSecond", "FireRate",
            "ClipSize", "ReloadTime", "ReloadDelay", "ReloadSingle", "BulletsPerShot", "BulletsPerBurst",
            "BurstInterShotInterval", "LightMeleeDamage", "HeavyMeleeDamage",
            "BulletSpeed", "FalloffStartRange", "FalloffEndRange",
            "CritDamageBonusPercent", "BulletRadius", "RoundsPerSecondAtMaxSpin", "SpinAcceleration", "SpinDeceleration"
        },
        Vitality = {
            "MaxHealth", "BaseHealthRegen", "BulletResist", "TechResist", "MeleeResist",
            "CritDamageReceivedPercent", "DebuffResist", "BulletLifesteal", "MaxMoveSpeed",
            "SprintSpeed", "StaminaCooldown", "Stamina", "GroundDashSpeed", "GravityChange"
        },
        Spirit = { "TechPower" }
    }

    -- Collect and sort heroes alphabetically, excluding disabled/in-development
    local sorted_heroes = {}
    for hero_key, hero_data in pairs(heroes_data) do
        if not hero_data["InDevelopment"] and not hero_data["IsDisabled"] then
            table.insert(sorted_heroes, {key = hero_key, data = hero_data})
        end
    end
    table.sort(sorted_heroes, function(a, b)
        local function get_sort_name(name)
            return (name:gsub("^The ", ""))
        end
        return get_sort_name(a.data["Name"] or a.key) < get_sort_name(b.data["Name"] or b.key)
    end)

    -- Build a single stat cell (<td>) with data attributes for JS recalculation
    local function buildStatCell(hero_data, hero_key, attr_key, is_alt_fire, category)
        -- Conversion factors for stats that need unit changes (e.g. metres → centimetres)
        local unit_conversion = {
            BulletRadius = 100  -- metres to centimetres
        }
        local conv_factor = unit_conversion[attr_key] or 1

        local base_value
        if is_alt_fire then
            if attr_key == "ClipSize" or attr_key == "ReloadTime" then
                base_value = get_nested_stat_value(hero_data, attr_key)
            elseif hero_data.Weapon and hero_data.Weapon.AltFire
                and hero_data.Weapon.AltFire[attr_key] ~= nil then
                base_value = hero_data.Weapon.AltFire[attr_key]
            else
                base_value = get_nested_stat_value(hero_data, attr_key)
            end
        else
            base_value = get_nested_stat_value(hero_data, attr_key)
        end

        -- Apply unit conversion to the base value
        if type(base_value) == "number" then
            base_value = base_value * conv_factor
        end

        local stat_value = base_value

        -- Scaling lookup
        local scaling_data
        if is_alt_fire then
            if attr_key == "ClipSize" or attr_key == "ReloadTime" then
                scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
            elseif (attr_key == "DPS" or attr_key == "SustainedDPS")
                and hero_data.Weapon and hero_data.Weapon.AltFire then
                -- Alt-fire DPS/SustainedDPS: use explicit key if present, otherwise compute from components
                local direct_scaling = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
                if direct_scaling and next(direct_scaling) ~= nil then
                    scaling_data = direct_scaling
                else
                    local alt_stats = hero_data.Weapon.AltFire
                    local dps_type = attr_key == "DPS" and 'burst' or 'sustained'
                    local level_scale = compute_dps_scaling(hero_data, alt_stats, dps_type, "Level")
                    local spirit_scale = compute_dps_scaling(hero_data, alt_stats, dps_type, "Spirit")
                    level_scale = util_module.round_to_sig_fig(level_scale, 5)
                    spirit_scale = util_module.round_to_sig_fig(spirit_scale, 5)
                    scaling_data = {}
                    if level_scale ~= 0 then scaling_data[level_scale] = "Level" end
                    if spirit_scale ~= 0 then scaling_data[spirit_scale] = "Spirit" end
                    if next(scaling_data) == nil then scaling_data = nil end
                end
            elseif hero_data.Weapon and hero_data.Weapon.AltFire
                and hero_data.Weapon.AltFire[attr_key] ~= nil then
                scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
            else
                scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
            end
        else
            scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
        end

        local scaling_strs = ""
        local spirit_scale = 0
        local level_scale  = 0
        local spirit_val = 0
        local level_val  = 0
        if scaling_data ~= nil then
            for scaling_val, scaling_type in pairs(scaling_data) do
                if scaling_type == "Spirit" then
                    spirit_val = scaling_val * conv_factor  -- apply unit conversion
                elseif scaling_type == "Level" then
                    level_val = scaling_val * conv_factor   -- apply unit conversion
                end
            end

            -- Output Spirit icon before Level icon
            local function append_scaling(val, stype)
                if val ~= 0 then
                    local scaling_str = hero_data_module.write_scalar_str(val, stype, true)
                    if scaling_str ~= "" then
                        scaling_strs = scaling_strs .. " " .. scaling_str
                    end
                end
            end
            append_scaling(spirit_val, "Spirit")
            append_scaling(level_val, "Level")

            if type(stat_value) == "number" then
                stat_value = stat_value + (spirit_power * spirit_val)
                stat_value = stat_value + (power_increases * level_val)
            end

            spirit_scale = spirit_val
            level_scale  = level_val
        end

        if attr_key == "TechPower" and spirit_scale == 0 then
            spirit_scale = 1.0
            if type(stat_value) == "number" then
                stat_value = stat_value + (spirit_power * spirit_scale)
            end
        end

        local innate_spirit_scale =
            (hero_data["LevelScaling"] and hero_data["LevelScaling"]["TechPower"]) or 0

        if not display_scaling_icons then scaling_strs = "" end

        if type(stat_value) == "boolean" then
            stat_value = tostring(stat_value)
        else
            stat_value = util_module.round_to_sig_fig(stat_value, 5)
        end

        local cell_inner = string.format(
            '<span class="stat-num">%s</span><span class="stat-scaling">%s</span>',
            stat_value,
            scaling_strs
        )

        local weapon_table = hero_data.Weapon
        if is_alt_fire and weapon_table and weapon_table.AltFire then
            weapon_table = weapon_table.AltFire
        end
        local hit_once = "false"
        if (attr_key == "DPS" or attr_key == "SustainedDPS")
            and weapon_table
            and weapon_table.HitOnceAcrossAllBullets
        then
            hit_once = "true"
        end

        local data_attrs = string.format(
            'data-stat-name="%s" data-base="%s" data-spirit-scale="%s" data-level-scale="%s" data-innate-spirit-scale="%s" data-sort-value="%s" data-hit-once="%s"',
            attr_key,
            tostring(type(base_value) == "number" and util_module.round_to_sig_fig(base_value, 3) or base_value),
            tonumber(spirit_scale) or 0,
            (attr_key == "TechPower") and "0" or (tonumber(level_scale) or 0),
            innate_spirit_scale or 0,
            stat_value,
            hit_once
        )

        return string.format('<td style="white-space: nowrap;" %s>%s</td>', data_attrs, cell_inner)
    end

    -- Generate a hero's primary stat row
    local function generatePrimaryRow(hero_data, hero_key, has_alt)
        local row_str = ""
        local hero_name_local = localize(hero_key, hero_key)
        local hero_name_en = hero_data["Name"]
        local template_args = {[1] = hero_name_en, l1 = hero_name_local}
        local hero_icon = mw.getCurrentFrame():expandTemplate{ title = "Template:HeroIcon", args = template_args }
        local hero_cell_content = hero_icon
        if has_alt then
            hero_cell_content = '[[#alt-fire-' .. hero_key .. '|+]] ' .. hero_cell_content
        end
        local sort_name = (hero_data["Name"] or hero_key):gsub("^The ", "")
        row_str = row_str .. '<td style="position: sticky; left: 0; z-index: 10; background-color: var(--background-color-base-2); isolation: isolate; overflow: hidden; min-width: 150px;" data-sort-value="' .. sort_name .. '">' .. hero_cell_content .. '</td>'
        for _, category in ipairs(attribute_orders["category_order"]) do
            if stats_to_include[category] ~= nil then
                for _, attr_key in ipairs(stats_to_include[category]) do
                    row_str = row_str .. buildStatCell(hero_data, hero_key, attr_key, false, category)
                end
            end
        end
        return "<tr>" .. row_str .. "</tr>"
    end

    -- Generate an expandable alt-fire sub-row (weapon stats only)
    local function generateAltFireSubRow(hero_data, hero_key)
        local row_str = ""
        local hero_name_local = localize(hero_key, hero_key)
        local hero_name_en = hero_data["Name"]
        local template_args = {[1] = hero_name_en, l1 = hero_name_local}
        local hero_icon = mw.getCurrentFrame():expandTemplate{ title = "Template:HeroIcon", args = template_args }
        local hero_cell_content = hero_icon .. ' <small style="color:#aaa;">(Alt‑fire)</small>'
        local sort_name = (hero_data["Name"] or hero_key):gsub("^The ", "")
        row_str = row_str .. '<td style="position: sticky; left: 0; z-index: 9; background-color: #202122; isolation: isolate; overflow: hidden; min-width: 150px;" data-sort-value="' .. sort_name .. '">' .. hero_cell_content .. '</td>'
        for _, category in ipairs(attribute_orders["category_order"]) do
            if stats_to_include[category] ~= nil then
                for _, attr_key in ipairs(stats_to_include[category]) do
                    if category == "Weapon" then
                        row_str = row_str .. buildStatCell(hero_data, hero_key, attr_key, true, category)
                    else
                        row_str = row_str .. '<td></td>'
                    end
                end
            end
        end
        return '<tr class="alt-fire-sub" data-parent="' .. hero_key .. '">' .. row_str .. '</tr>'
    end

    -- Build all body rows
    for _, hero_entry in ipairs(sorted_heroes) do
        local hero_key  = hero_entry.key
        local hero_data = hero_entry.data
        local has_alt = hero_data.Weapon and hero_data.Weapon.AltFire and true or false
        body_str = body_str .. generatePrimaryRow(hero_data, hero_key, has_alt)
        if has_alt then
            body_str = body_str .. generateAltFireSubRow(hero_data, hero_key)
        end
    end

    -- Pre-pass: determine which stats have any scaling, and which have both types.
    -- Used to set column widths in the header.
    local stats_with_any_scaling  = {}
    local stats_with_both_scaling = {}
    for _, hero_entry in ipairs(sorted_heroes) do
        local hero_data = hero_entry.data
        for _, category in ipairs(attribute_orders["category_order"]) do
            if stats_to_include[category] ~= nil then
                for _, attr_key in ipairs(stats_to_include[category]) do
                    -- Primary scaling
                    local scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
                    if scaling_data ~= nil and next(scaling_data) ~= nil then
                        stats_with_any_scaling[attr_key] = true
                        local has_spirit, has_level = false, false
                        for _, scaling_type in pairs(scaling_data) do
                            if scaling_type == "Spirit" then has_spirit = true
                            elseif scaling_type == "Level" then has_level = true end
                        end
                        if has_spirit and has_level then stats_with_both_scaling[attr_key] = true end
                    end

                    -- Alt-fire scaling (only for stats present in the AltFire table)
                    if hero_data.Weapon
                        and hero_data.Weapon.AltFire
                        and hero_data.Weapon.AltFire[attr_key] ~= nil
                    then
                        if attr_key ~= "ClipSize" then
                            local alt_scaling = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
                            if alt_scaling and next(alt_scaling) ~= nil then
                                stats_with_any_scaling[attr_key] = true
                                local has_spirit_alt, has_level_alt = false, false
                                for _, stype in pairs(alt_scaling) do
                                    if stype == "Spirit" then has_spirit_alt = true
                                    elseif stype == "Level" then has_level_alt = true end
                                end
                                if has_spirit_alt and has_level_alt then stats_with_both_scaling[attr_key] = true end
                            else
                                if attr_key == "DPS" or attr_key == "SustainedDPS" then
                                    local alt_stats = hero_data.Weapon.AltFire
                                    local dps_type = attr_key == "DPS" and 'burst' or 'sustained'
                                    local lv = compute_dps_scaling(hero_data, alt_stats, dps_type, "Level")
                                    local sp = compute_dps_scaling(hero_data, alt_stats, dps_type, "Spirit")
                                    lv = util_module.round_to_sig_fig(lv, 5)
                                    sp = util_module.round_to_sig_fig(sp, 5)
                                    if lv ~= 0 or sp ~= 0 then
                                        stats_with_any_scaling[attr_key] = true
                                        if lv ~= 0 and sp ~= 0 then
                                            stats_with_both_scaling[attr_key] = true
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end
    end

    -- Build table header row
    local headers_str = '<th style="position: sticky; left: 0; top: -1px; z-index: 12; background-color: var(--background-color-base-5); isolation: isolate; min-width: 150px;">Hero</th>'
    local category_data = attribute_module.get_category_data()
    local postfix_key_map = {
        ["ReloadDelay"] = "StatDesc_ReloadTime_postfix",
        ["BulletsPerShot"] = "",
        ["BulletsPerBurst"] = "",
        ["BurstInterShotInterval"] = "StatDesc_ReloadTime_postfix",
        ["ReloadSingle"] = "",
        ["BonusAttackRange"] = "StatDesc_WeaponRangeFalloffMax_postfix",
        ["SustainedDPS"] = "DPS_postfix",
        ["RoundsPerSecondAtMaxSpin"] = "",
        ["CritDamageBonusPercent"]   = "StatDesc_CritDamageBonusScale_postfix",
		["CritDamageReceivedPercent"] = "StatDesc_CritDamageReceivedScale_postfix",
        ["BulletLifesteal"] = "BulletLifestealPercentHero_postfix",
        ["GroundDashSpeed"] = "DashSpeed_postfix"
    }
    for _, category in ipairs(attribute_orders["category_order"]) do
        local category_attrs = attributes_data[category]
        local category_rgb   = category_data[category]["rgb"]
        if stats_to_include[category] ~= nil then
            for _, attr_key in ipairs(stats_to_include[category]) do
                local attr_data = category_attrs[attr_key]
                
                -- Fallback: if the stat is missing from this category, check all other categories
                if attr_data == nil then
                    for _, fallback_cat_data in pairs(attributes_data) do
                        if fallback_cat_data[attr_key] ~= nil then
                            attr_data = fallback_cat_data[attr_key]
                            break
                        end
                    end
                end

                local attr_localized, postfix
                if attr_data ~= nil then
                    attr_localized = lang_module.get_string(attr_data["label"])
                    if attr_localized == nil or attr_localized == "" then
                        attr_localized = util_module.add_space_before_cap(attr_key)
                    end
                    postfix = lang_module.get_string(attr_data["postfix"])
                    if postfix == nil or postfix == "" then postfix = ""
                    else postfix = " (" .. postfix .. ")" end
                    if attr_key == "BulletRadius" then postfix = " (cm)" end
                else
                    attr_localized = dictionary_module.translate(attr_key)
                    postfix = lang_module.get_string(postfix_key_map[attr_key])
                    if postfix == nil then return "attr_key " .. attr_key .. " must be added to postfix_key_map" end
                    if postfix ~= "" then postfix = " (" .. postfix .. ")" end
                end
                local th_style = 'position: sticky; top: -1px; z-index: 3; background-color: rgb(' .. category_rgb .. ');'
                if stats_with_both_scaling[attr_key] then
                    th_style = th_style .. ' min-width: 130px;'
                elseif stats_with_any_scaling[attr_key] then
                    th_style = th_style .. ' min-width: 75px;'
                end
                headers_str = headers_str .. '<th style="' .. th_style .. '">' .. attr_localized .. postfix .. "</th>"
            end
        end
    end
    headers_str = "<tr>" .. headers_str .. "</tr>"

    return string.format(
        '<div id="hero-comparison-container" data-max-power="%s" data-max-spirit="%s">' ..
        '<div style="overflow: auto; max-height: 70vh; width: 100%%;">' ..
        '<table class="wikitable sortable" style="table-layout: auto; width: 100%%;" id="hero-comparison-table">%s%s</table>' ..
        '</div></div>',
        max_power, max_spirit, headers_str, body_str
    )
end

return p