require 'Items/ProceduralDistributions'
require 'Items/SuburbsDistributions'
require 'Items/Distributions'
require 'Items/Distribution_BinJunk'
require 'Items/Distribution_ClosetJunk'
require 'Items/Distribution_DeskJunk'
require 'Items/Distribution_ShelfJunk'
require 'Items/Distribution_CounterJunk'
require 'Items/Distribution_SideTableJunk'
require 'Vehicles/VehicleDistributions'
require 'Vehicles/VehicleDistribution_GloveBoxJunk'
require 'Vehicles/VehicleDistribution_SeatJunk'
require 'Vehicles/VehicleDistribution_TrunkJunk'

----------------- TOW BAR -----------------------
-- Mirror Jack spawn chance into TowBar in container distributions (world + vehicle containers).
-- Intentionally excludes story-clutter floor placement tables (RandomizedWorldContent/StoryClutter).

local TOWBAR_ITEM_TYPE = "TowBar.TowBar"
local JACK_ITEM_TYPES = {
    ["Jack"] = true,
    ["Base.Jack"] = true,
}

local function addMissingTowBarsForJack(items)
    if type(items) ~= "table" then return end

    local jackCountByChance = {}
    local towBarCountByChance = {}

    for i = 1, #items, 2 do
        local itemType = items[i]
        local chance = tonumber(items[i + 1])
        if type(itemType) == "string" and chance ~= nil then
            if JACK_ITEM_TYPES[itemType] then
                jackCountByChance[chance] = (jackCountByChance[chance] or 0) + 1
            elseif itemType == TOWBAR_ITEM_TYPE then
                towBarCountByChance[chance] = (towBarCountByChance[chance] or 0) + 1
            end
        end
    end

    for chance, jackCount in pairs(jackCountByChance) do
        local missing = jackCount - (towBarCountByChance[chance] or 0)
        for _ = 1, missing do
            table.insert(items, TOWBAR_ITEM_TYPE)
            table.insert(items, chance)
        end
    end
end

local function walkContainerDistributions(root, seen)
    if type(root) ~= "table" or seen[root] then return end
    seen[root] = true

    for key, value in pairs(root) do
        if key == "items" and type(value) == "table" then
            addMissingTowBarsForJack(value)
        elseif type(value) == "table" then
            walkContainerDistributions(value, seen)
        end
    end
end

local seen = {}
walkContainerDistributions(ProceduralDistributions, seen)
walkContainerDistributions(SuburbsDistributions, seen)
walkContainerDistributions(Distributions, seen)
walkContainerDistributions(VehicleDistributions, seen)
walkContainerDistributions(ClutterTables, seen)

