Модуль:Песочница/Pok: различия между версиями

Материал из Space Station 14 Вики
мНет описания правки
мНет описания правки
Строка 4: Строка 4:
-- Загрузка данных  
-- Загрузка данных  
---------------------------------------------------------------------
---------------------------------------------------------------------
local itemData           = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local itemData             = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local tableData         = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local tableData           = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local gearData           = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local gearData             = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local jobData           = mw.loadData("Модуль:IanComradeBot/job.json/data")
local jobData             = mw.loadData("Модуль:IanComradeBot/job.json/data")
local gearRoleLoadout   = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local gearRoleLoadout     = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local loadoutData       = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local loadoutData         = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local loadoutGroupData   = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local loadoutGroupData     = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local cargoData         = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
local cargoData           = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
local latheData         = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local latheData           = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local recipeData         = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local recipeData           = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local researchData       = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local researchData         = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local materialData       = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local materialData         = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local chemDataLathe     = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local chemDataLathe       = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local vendingMachinesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local vendingMachinesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local inventoriesData     = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")
local inventoriesData     = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Функции для обратного поиска
-- Вспомогательные функции
---------------------------------------------------------------------
---------------------------------------------------------------------


local function searchItemInStructure(struct, targetId)
-- Обобщённый рекурсивный поиск по полю key с условием predicate
local function searchInStructure(struct, key, predicate)
     if type(struct) ~= "table" then
     if type(struct) ~= "table" then
         return false
         return false
     end
     end
     if struct.id and struct.id == targetId then
     if struct[key] and predicate(struct[key]) then
         return true
         return true
     end
     end
     for _, v in pairs(struct) do
     for _, v in pairs(struct) do
         if type(v) == "table" then
         if type(v) == "table" and searchInStructure(v, key, predicate) then
            if searchItemInStructure(v, targetId) then
            return true
                return true
            end
         end
         end
     end
     end
Строка 41: Строка 40:
end
end


local function searchItemInStructure(struct, targetId)
    return searchInStructure(struct, "id", function(val) return val == targetId end)
end
local function searchTableIdInStructure(struct, tableIds)
    return searchInStructure(struct, "tableId", function(val)
        for _, tid in ipairs(tableIds) do
            if val == tid then return true end
        end
        return false
    end)
end
-- Формирование ссылки для сущности (используется в reverseContained, reverseLathe, reverseVending)
local function createEntityLink(entityId)
    local nameCode = "{{#invoke:Entity Lookup|getname|" .. entityId .. "}}"
    return "[[" .. nameCode .. "|" .. nameCode .. "]]"
end
-- Формирование ссылки для таблицы грузов (reverseCargo)
local function createCargoLink(storage)
    local nameCode = "{{#invoke:Entity Lookup|getname|" .. storage .. "}}"
    return "[[Таблица грузов#" .. nameCode .. "|" .. nameCode .. "]]"
end
-- Формирование ссылки для роли/джоба (reverseEquipment)
local function createJobLink(jobId)
    local translation = "{{#invoke:Ftl|main|translation|" .. jobId .. "}}"
    return "[[" .. translation .. "|{{ucfirst:" .. translation .. "}}]]"
end
---------------------------------------------------------------------
-- Логика поиска
---------------------------------------------------------------------
---------------------------------------------------------------------


local function findRelatedTables(initialList)
local function findRelatedTables(initialList)
     local results = {}  
     local results = {}
     local function recursiveSearch(tblId)
     local function recursiveSearch(tblId)
         if results[tblId] then  
         if results[tblId] then  
Строка 53: Строка 85:
             if type(entry) == "table" then
             if type(entry) == "table" then
                 for _, value in pairs(entry) do
                 for _, value in pairs(entry) do
                     if type(value) == "table" and value.tableId and value.tableId == tblId then
                     if type(value) == "table" and value.tableId == tblId then
                         recursiveSearch(id)
                         recursiveSearch(id)
                     end
                     end
Строка 70: Строка 102:
end
end


local function searchTableIdInStructure(struct, tableIds)
    if type(struct) ~= "table" then
        return false
    end
    if struct.tableId then
        for _, tid in ipairs(tableIds) do
            if struct.tableId == tid then
                return true
            end
        end
    end
    for _, v in pairs(struct) do
        if type(v) == "table" then
            if searchTableIdInStructure(v, tableIds) then
                return true
            end
        end
    end
    return false
end
---------------------------------------------------------------------
-- Общая логика поиска хранилищ, содержащих указанный targetId
---------------------------------------------------------------------
local function findMatchingStorages(targetId)
local function findMatchingStorages(targetId)
     local initialTables = {}
     local initialTables = {}
     for key, tblEntry in pairs(tableData) do
     for key, tblEntry in pairs(tableData) do
         if type(tblEntry) == "table" then
         if type(tblEntry) == "table" and searchItemInStructure(tblEntry, targetId) then
            if searchItemInStructure(tblEntry, targetId) then
            local tableId = tblEntry.id or key
                local tableId = tblEntry.id or key
            table.insert(initialTables, tableId)
                table.insert(initialTables, tableId)
            end
         end
         end
     end
     end


     local allRelatedTables = {}
     local allRelatedTables = (#initialTables > 0) and findRelatedTables(initialTables) or {}
    if #initialTables > 0 then
        allRelatedTables = findRelatedTables(initialTables)
    end


     local matchingStorages = {}
     local matchingStorages = {}
Строка 114: Строка 117:
         if type(storage) == "table" then
         if type(storage) == "table" then
             local found = false
             local found = false
             if storage.EntityTableContainerFill  
             if storage.EntityTableContainerFill  
               and storage.EntityTableContainerFill.containers then
               and storage.EntityTableContainerFill.containers then
Строка 121: Строка 123:
                 end
                 end
             end
             end
             if searchItemInStructure(storage, targetId) then
             if searchItemInStructure(storage, targetId) then
                 found = true
                 found = true
             end
             end
             if found then
             if found then
                 local actualId = storage.id or storageKey
                 local actualId = storage.id or storageKey
Строка 137: Строка 137:


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Функции обратного поиска
---------------------------------------------------------------------
function p.reverseContained(frame)
function p.reverseContained(frame)
     local targetId = frame.args[2]
     local targetId = frame.args[2]
Строка 162: Строка 165:
     end
     end


local filteredStoragesLinks = {}
    local links = {}
for _, storage in ipairs(filteredStorages) do
    for _, storage in ipairs(filteredStorages) do
    table.insert(filteredStoragesLinks, "[[{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
        table.insert(links, createEntityLink(storage))
end
    end


     return "Находится в хранилище: " .. table.concat(filteredStoragesLinks, ", ")
     return "Находится в хранилище: " .. table.concat(links, ", ")
end
end


---------------------------------------------------------------------
function p.reverseEquipment(frame)
function p.reverseEquipment(frame)
     local targetId = frame.args[2]
     local targetId = frame.args[2]
Строка 194: Строка 196:
                     end
                     end
                     if foundJob then
                     if foundJob then
                         table.insert(results, "[[{{#invoke:Ftl|main|translation|" .. foundJob .. "}}|{{ucfirst:{{#invoke:Ftl|main|translation|" .. foundJob .. "}}}}]]")
                         table.insert(results, createJobLink(foundJob))
                     end
                     end
                 end
                 end
Строка 207: Строка 209:
                 if equipId == targetId and (not slotFilter or slot == slotFilter) then
                 if equipId == targetId and (not slotFilter or slot == slotFilter) then
                     local foundGroupId = nil
                     local foundGroupId = nil
                    -- Поиск группы в loadoutGroupData, в которой присутствует loadout.id
                     for _, group in pairs(loadoutGroupData) do
                     for _, group in pairs(loadoutGroupData) do
                         if group.loadouts and type(group.loadouts) == "table" then
                         if group.loadouts and type(group.loadouts) == "table" then
Строка 220: Строка 221:
                     end
                     end
                     local foundJob = nil
                     local foundJob = nil
                    -- Поиск роли в gearRoleLoadout, где группы содержат найденный id группы
                     if foundGroupId then
                     if foundGroupId then
                         for _, role in pairs(gearRoleLoadout) do
                         for _, role in pairs(gearRoleLoadout) do
Строка 235: Строка 235:
                     end
                     end
                     if foundJob then
                     if foundJob then
                         table.insert(results, "[[{{#invoke:Ftl|main|translation|" .. foundJob .. "}}|{{ucfirst:{{#invoke:Ftl|main|translation|" .. foundJob .. "}}}}]]")
                         table.insert(results, createJobLink(foundJob))
                     end
                     end
                 end
                 end
Строка 249: Строка 249:
end
end


---------------------------------------------------------------------
function p.reverseCargo(frame)
function p.reverseCargo(frame)
     local searchValue = frame.args[2]
     local searchValue = frame.args[2]
Строка 256: Строка 255:
     end
     end


     -- Сначала ищем прямые совпадения в cargoData по product
     -- Сначала ищем прямые совпадения по product
     local directCargo = {}
     local directCargo = {}
     for _, entry in ipairs(cargoData) do
     for _, entry in ipairs(cargoData) do
Строка 268: Строка 267:
     end
     end


     -- Если не найдено прямых совпадений, выполняем обратный поиск как в reverseContained,
     -- Если прямых совпадений нет, выполняем обратный поиск среди хранилищ
    -- но оставляем только те хранилища, которые присутствуют в cargoData (т.е. имеют product равный их id)
     local matchingStorages = findMatchingStorages(searchValue)
     local matchingStorages = findMatchingStorages(searchValue)
     local cargoStorages = {}
     local cargoStorages = {}
Строка 284: Строка 282:
         return ""
         return ""
     end
     end
      
 
local cargoLinks = {}
     local links = {}
for _, storage in ipairs(cargoStorages) do
    for _, storage in ipairs(cargoStorages) do
    table.insert(cargoLinks, "[[Таблица грузов#{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
        table.insert(links, createCargoLink(storage))
end
    end
return "Заказ груза: " .. table.concat(cargoLinks, ", ")
    return "Заказ груза: " .. table.concat(links, ", ")
end
end


---------------------------------------------------------------------
local function getRecipeById(recipeId)
local function getRecipeById(recipeId)
     for _, recipe in ipairs(recipeData) do
     for _, recipe in ipairs(recipeData) do
Строка 340: Строка 337:
     end
     end


local matchingLathesLinks = {}
    local links = {}
for _, storage in ipairs(matchingLathes) do
    for _, latheId in ipairs(matchingLathes) do
    table.insert(matchingLathesLinks, "[[{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
        table.insert(links, createEntityLink(latheId))
end
    end


     return "Может быть напечатано на станке: " .. table.concat(matchingLathesLinks, ", ")
     return "Может быть напечатано на станке: " .. table.concat(links, ", ")
end
end


---------------------------------------------------------------------
function p.reverseVending(frame)
function p.reverseVending(frame)
     local invMode = frame.args[2] or ""  -- режим поиска: "inventory", "contraband", "emag" или пустая строка для всех
     local invMode = frame.args[2] or ""  -- режим: "inventory", "contraband", "emag" или пустая строка для всех
     local targetId = frame.args[3]
     local targetId = frame.args[3]
     if not targetId or targetId == "" then
     if not targetId or targetId == "" then
         return "Ошибка: не указан id предмета для обратного поиска в торговых автоматах."
         return "Ошибка: не указан id предмета для обратного поиска в торговых автоматах."
     end
     end
    -- Определяем соответствующие ключи для поиска в инвентарях
    local inventoryTypes = {
        inventory  = "startingInventory",
        contraband  = "contrabandInventory",
        emag        = "emaggedInventory"
    }


     local matchingInventoryIds = {}
     local matchingInventoryIds = {}
    -- Перебираем все инвентарные записи
     for _, inventory in pairs(inventoriesData) do
     for _, inventory in pairs(inventoriesData) do
         if inventory.id then
         if inventory.id then
             local found = false
             local found = false
             if (invMode == "inventory" or invMode == "" or not invMode) and inventory.startingInventory and type(inventory.startingInventory) == "table" then
             if invMode ~= "" then
                if inventory.startingInventory[targetId] then
                local key = inventoryTypes[invMode]
                if key and inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
                     found = true
                     found = true
                 end
                 end
             end
             else
            if (invMode == "contraband" or invMode == "" or not invMode) and inventory.contrabandInventory and type(inventory.contrabandInventory) == "table" then
                for _, key in pairs(inventoryTypes) do
                if inventory.contrabandInventory[targetId] then
                    if inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
                    found = true
                        found = true
                end
                        break
            end
                    end
            if (invMode == "emag" or invMode == "" or not invMode) and inventory.emaggedInventory and type(inventory.emaggedInventory) == "table" then
                if inventory.emaggedInventory[targetId] then
                    found = true
                 end
                 end
             end
             end
Строка 389: Строка 389:
     for _, vm in pairs(vendingMachinesData) do
     for _, vm in pairs(vendingMachinesData) do
         if vm.VendingMachine and vm.VendingMachine.pack then
         if vm.VendingMachine and vm.VendingMachine.pack then
            local packId = vm.VendingMachine.pack
             for _, invId in ipairs(matchingInventoryIds) do
             for _, invId in ipairs(matchingInventoryIds) do
                 if packId == invId then
                 if vm.VendingMachine.pack == invId then
                     if vm.id then
                     if vm.id then
                         table.insert(matchingVendingMachines, vm.id)
                         table.insert(matchingVendingMachines, vm.id)
Строка 404: Строка 403:
         return ""
         return ""
     end
     end
   
    local matchingVendingMachinesLinks = {}
for _, storage in ipairs(matchingVendingMachines) do
    table.insert(matchingVendingMachinesLinks, "[[{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
end


     return "Содержится в торгомате: " .. table.concat(matchingVendingMachinesLinks, ", ")
     local links = {}
    for _, vmId in ipairs(matchingVendingMachines) do
        table.insert(links, createEntityLink(vmId))
    end
 
    -- Разные текстовые сообщения для каждого режима
    local modeTexts = {
        inventory  = "В торговом автомате (инвентарь): ",
        contraband = "В торговом автомате (контрабанда): ",
        emag      = "В торговом автомате (эмаг): "
    }
    local outputText = modeTexts[invMode] or "Содержится в торгомате: "
    return outputText .. table.concat(links, ", ")
end
end



Версия от 21:00, 21 февраля 2025

Для документации этого модуля может быть создана страница Модуль:Песочница/Pok/doc

local p = {}

---------------------------------------------------------------------
-- Загрузка данных 
---------------------------------------------------------------------
local itemData             = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local tableData            = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local gearData             = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local jobData              = mw.loadData("Модуль:IanComradeBot/job.json/data")
local gearRoleLoadout      = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local loadoutData          = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local loadoutGroupData     = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local cargoData            = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
local latheData            = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local recipeData           = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local researchData         = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local materialData         = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local chemDataLathe        = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local vendingMachinesData  = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local inventoriesData      = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")

---------------------------------------------------------------------
-- Вспомогательные функции
---------------------------------------------------------------------

-- Обобщённый рекурсивный поиск по полю key с условием predicate
local function searchInStructure(struct, key, predicate)
    if type(struct) ~= "table" then
        return false
    end
    if struct[key] and predicate(struct[key]) then
        return true
    end
    for _, v in pairs(struct) do
        if type(v) == "table" and searchInStructure(v, key, predicate) then
            return true
        end
    end
    return false
end

local function searchItemInStructure(struct, targetId)
    return searchInStructure(struct, "id", function(val) return val == targetId end)
end

local function searchTableIdInStructure(struct, tableIds)
    return searchInStructure(struct, "tableId", function(val)
        for _, tid in ipairs(tableIds) do
            if val == tid then return true end
        end
        return false
    end)
end

-- Формирование ссылки для сущности (используется в reverseContained, reverseLathe, reverseVending)
local function createEntityLink(entityId)
    local nameCode = "{{#invoke:Entity Lookup|getname|" .. entityId .. "}}"
    return "[[" .. nameCode .. "|" .. nameCode .. "]]"
end

-- Формирование ссылки для таблицы грузов (reverseCargo)
local function createCargoLink(storage)
    local nameCode = "{{#invoke:Entity Lookup|getname|" .. storage .. "}}"
    return "[[Таблица грузов#" .. nameCode .. "|" .. nameCode .. "]]"
end

-- Формирование ссылки для роли/джоба (reverseEquipment)
local function createJobLink(jobId)
    local translation = "{{#invoke:Ftl|main|translation|" .. jobId .. "}}"
    return "[[" .. translation .. "|{{ucfirst:" .. translation .. "}}]]"
end

---------------------------------------------------------------------
-- Логика поиска
---------------------------------------------------------------------

local function findRelatedTables(initialList)
    local results = {}
    local function recursiveSearch(tblId)
        if results[tblId] then 
            return 
        end
        results[tblId] = true
        for id, entry in pairs(tableData) do
            if type(entry) == "table" then
                for _, value in pairs(entry) do
                    if type(value) == "table" and value.tableId == tblId then
                        recursiveSearch(id)
                    end
                end
            end
        end
    end
    for _, tblId in ipairs(initialList) do
        recursiveSearch(tblId)
    end
    local res = {}
    for id in pairs(results) do 
        table.insert(res, id)
    end
    return res
end

local function findMatchingStorages(targetId)
    local initialTables = {}
    for key, tblEntry in pairs(tableData) do
        if type(tblEntry) == "table" and searchItemInStructure(tblEntry, targetId) then
            local tableId = tblEntry.id or key
            table.insert(initialTables, tableId)
        end
    end

    local allRelatedTables = (#initialTables > 0) and findRelatedTables(initialTables) or {}

    local matchingStorages = {}
    for storageKey, storage in pairs(itemData) do
        if type(storage) == "table" then
            local found = false
            if storage.EntityTableContainerFill 
               and storage.EntityTableContainerFill.containers then
                if searchTableIdInStructure(storage.EntityTableContainerFill.containers, allRelatedTables) then
                    found = true
                end
            end
            if searchItemInStructure(storage, targetId) then
                found = true
            end
            if found then
                local actualId = storage.id or storageKey
                table.insert(matchingStorages, actualId)
            end
        end
    end

    return matchingStorages
end

---------------------------------------------------------------------
-- Функции обратного поиска
---------------------------------------------------------------------

function p.reverseContained(frame)
    local targetId = frame.args[2]
    if not targetId or targetId == "" then
        return "Ошибка: не указан id предмета для обратного поиска."
    end

    local matchingStorages = findMatchingStorages(targetId)
    local filteredStorages = {}
    for _, sid in ipairs(matchingStorages) do
        local skip = false
        for _, cargo in pairs(cargoData) do
            if type(cargo) == "table" and cargo.product == sid then
                skip = true
                break
            end
        end
        if not skip then
            table.insert(filteredStorages, sid)
        end
    end

    if #filteredStorages == 0 then
        return ""
    end

    local links = {}
    for _, storage in ipairs(filteredStorages) do
        table.insert(links, createEntityLink(storage))
    end

    return "Находится в хранилище: " .. table.concat(links, ", ")
end

function p.reverseEquipment(frame)
    local targetId = frame.args[2]
    local slotFilter = frame.args[3]
    if not targetId or targetId == "" then
        return "Ошибка: не указан id оборудования для обратного поиска."
    end

    local results = {}

    -- Обработка startingGear (gearData)
    for _, gear in pairs(gearData) do
        local currentGearId = gear.id or "Unknown"
        if gear.equipment then
            for slot, equipId in pairs(gear.equipment) do
                if equipId == targetId and (not slotFilter or slot == slotFilter) then
                    local foundJob = nil
                    for jobId, job in pairs(jobData) do
                        if job.startingGear == currentGearId then
                            foundJob = jobId
                            break
                        end
                    end
                    if foundJob then
                        table.insert(results, createJobLink(foundJob))
                    end
                end
            end
        end
    end

    -- Обработка loadout (loadoutData)
    for _, loadout in pairs(loadoutData) do
        if loadout.equipment then
            for slot, equipId in pairs(loadout.equipment) do
                if equipId == targetId and (not slotFilter or slot == slotFilter) then
                    local foundGroupId = nil
                    for _, group in pairs(loadoutGroupData) do
                        if group.loadouts and type(group.loadouts) == "table" then
                            for _, lId in ipairs(group.loadouts) do
                                if lId == loadout.id then
                                    foundGroupId = group.id
                                    break
                                end
                            end
                        end
                        if foundGroupId then break end
                    end
                    local foundJob = nil
                    if foundGroupId then
                        for _, role in pairs(gearRoleLoadout) do
                            if role.groups then
                                for _, g in ipairs(role.groups) do
                                    if g == foundGroupId then
                                        foundJob = role.id
                                        break
                                    end
                                end
                            end
                            if foundJob then break end
                        end
                    end
                    if foundJob then
                        table.insert(results, createJobLink(foundJob))
                    end
                end
            end
        end
    end

    if #results == 0 then
        return "Оборудование с id " .. targetId .. " не найдено в наборах экипировки."
    end

    return "Начальная экипировка роли: " .. table.concat(results, ", ")
end

function p.reverseCargo(frame)
    local searchValue = frame.args[2]
    if not searchValue or searchValue == "" then
        return "Ошибка: не указано значение для поиска в режиме cargo."
    end

    -- Сначала ищем прямые совпадения по product
    local directCargo = {}
    for _, entry in ipairs(cargoData) do
        if entry.product == searchValue then
            table.insert(directCargo, entry.id)
        end
    end

    if #directCargo > 0 then
        return "Найденные записи cargo: " .. table.concat(directCargo, ", ")
    end

    -- Если прямых совпадений нет, выполняем обратный поиск среди хранилищ
    local matchingStorages = findMatchingStorages(searchValue)
    local cargoStorages = {}
    for _, sid in ipairs(matchingStorages) do
        for _, cargo in pairs(cargoData) do
            if type(cargo) == "table" and cargo.product == sid then
                table.insert(cargoStorages, sid)
                break
            end
        end
    end

    if #cargoStorages == 0 then
        return ""
    end

    local links = {}
    for _, storage in ipairs(cargoStorages) do
        table.insert(links, createCargoLink(storage))
    end
    return "Заказ груза: " .. table.concat(links, ", ")
end

local function getRecipeById(recipeId)
    for _, recipe in ipairs(recipeData) do
        if recipe.id == recipeId then
            return recipe
        end
    end
    return nil
end

function p.reverseLathe(frame)
    local targetResult = frame.args[2]
    if not targetResult or targetResult == "" then
        return "Ошибка: не указан результат рецепта для обратного поиска."
    end

    local matchingLathes = {}
    local function checkRecipes(recipeIds)
        for _, recipeId in ipairs(recipeIds or {}) do
            local recipe = getRecipeById(recipeId)
            if recipe and recipe.result == targetResult then
                return true
            end
        end
        return false
    end

    for _, lathe in ipairs(latheData) do
        local found = false
        if lathe.Lathe then
            if checkRecipes(lathe.Lathe.staticRecipes) or checkRecipes(lathe.Lathe.dynamicRecipes) then
                found = true
            end
        end
        if not found and lathe.EmagLatheRecipes then
            if checkRecipes(lathe.EmagLatheRecipes.emagStaticRecipes) or checkRecipes(lathe.EmagLatheRecipes.emagDynamicRecipes) then
                found = true
            end
        end
        if found and lathe.id then
            table.insert(matchingLathes, lathe.id)
        end
    end

    if #matchingLathes == 0 then
        return ""
    end

    local links = {}
    for _, latheId in ipairs(matchingLathes) do
        table.insert(links, createEntityLink(latheId))
    end

    return "Может быть напечатано на станке: " .. table.concat(links, ", ")
end

function p.reverseVending(frame)
    local invMode = frame.args[2] or ""   -- режим: "inventory", "contraband", "emag" или пустая строка для всех
    local targetId = frame.args[3]
    if not targetId or targetId == "" then
        return "Ошибка: не указан id предмета для обратного поиска в торговых автоматах."
    end

    -- Определяем соответствующие ключи для поиска в инвентарях
    local inventoryTypes = {
        inventory   = "startingInventory",
        contraband  = "contrabandInventory",
        emag        = "emaggedInventory"
    }

    local matchingInventoryIds = {}
    for _, inventory in pairs(inventoriesData) do
        if inventory.id then
            local found = false
            if invMode ~= "" then
                local key = inventoryTypes[invMode]
                if key and inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
                    found = true
                end
            else
                for _, key in pairs(inventoryTypes) do
                    if inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
                        found = true
                        break
                    end
                end
            end
            if found then
                table.insert(matchingInventoryIds, inventory.id)
            end
        end
    end

    if #matchingInventoryIds == 0 then
        return ""
    end

    local matchingVendingMachines = {}
    for _, vm in pairs(vendingMachinesData) do
        if vm.VendingMachine and vm.VendingMachine.pack then
            for _, invId in ipairs(matchingInventoryIds) do
                if vm.VendingMachine.pack == invId then
                    if vm.id then
                        table.insert(matchingVendingMachines, vm.id)
                    end
                    break
                end
            end
        end
    end

    if #matchingVendingMachines == 0 then
        return ""
    end

    local links = {}
    for _, vmId in ipairs(matchingVendingMachines) do
        table.insert(links, createEntityLink(vmId))
    end

    -- Разные текстовые сообщения для каждого режима
    local modeTexts = {
        inventory  = "В торговом автомате (инвентарь): ",
        contraband = "В торговом автомате (контрабанда): ",
        emag       = "В торговом автомате (эмаг): "
    }
    local outputText = modeTexts[invMode] or "Содержится в торгомате: "
    return outputText .. table.concat(links, ", ")
end

---------------------------------------------------------------------
-- Основная функция модуля
---------------------------------------------------------------------
function p.main(frame)
    local mode = frame.args[1]
    if not mode or mode == "" then
        return "Ошибка: не указан режим обратного поиска. Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe, reverseVending."
    end

    if mode == "reverseContained" then
        return mw.getCurrentFrame():preprocess(p.reverseContained(frame))
    elseif mode == "reverseEquipment" then
        return mw.getCurrentFrame():preprocess(p.reverseEquipment(frame))
    elseif mode == "reverseCargo" then
        return mw.getCurrentFrame():preprocess(p.reverseCargo(frame))
    elseif mode == "reverseLathe" then
        return mw.getCurrentFrame():preprocess(p.reverseLathe(frame))
    elseif mode == "reverseVending" then
        return mw.getCurrentFrame():preprocess(p.reverseVending(frame))
    else
        return "Неизвестный режим: " .. mode .. ". Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe, reverseVending."
    end
end

return p