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

мНет описания правки
Нет описания правки
 
(не показаны 233 промежуточные версии этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local p = {}
local itemData          = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local itemSlotsData    = mw.loadData("Модуль:IanComradeBot/prototypes/ItemSlots.json/data")
local itemStackData    = mw.loadData("Модуль:IanComradeBot/prototypes/fills/stack.json/data")
local chemData          = mw.loadData("Модуль:IanComradeBot/prototypes/fills/chem.json/data")
local chemTranslateData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")


local p = {}
local BASE_USER = "IanComradeBot/"


-- Функция для загрузки данных
local function get_module_name(pagePath)
local loadData = function(filePath)
     return "Module:" .. BASE_USER .. pagePath .. "/data"
     local page = mw.title.new(filePath)
    local content = page:getContent()
    return content and mw.text.jsonDecode(content) or nil
end
end


-- Функция processRolls для преобразования диапазона
local function load_cached_data(moduleName)
local processRolls = function(rolls)
     local ok, loaded = pcall(mw.loadData, moduleName)
     local result = ""
     if not ok or not loaded then
    if rolls and rolls.range then
         return nil
        -- Если указан range
        local min, max = rolls.range:match("(%d+),%s*(%d+)")
        min, max = tonumber(min), tonumber(max)
        if min and max then
            result = result .. string.format('[%d-%d]', min + 1, max + 1)
        else
            result = result .. 'Некорректный формат для range.'
        end
     elseif rolls and rolls.value then
         -- Если указано value
        result = result .. string.format('[%d]', rolls.value)
    else
        result = result .. 'Не указан параметр rolls.'
     end
     end
     return result
     return loaded
end
end


-- Функция для поиска первого startingItem в slots
local function parse_indexed_part(part)
local function getFirstStartingItem(data)
    local key, idx = string.match(part, "^(.-)%[(%d+)%]$")
     if not data or not data.ItemSlots or not data.ItemSlots.slots then  
    if key then
         return nil  
        return key, tonumber(idx)
    end
    local num = tonumber(part)
     if num then
         return nil, num
     end
     end
      
     return part, nil
     for _, slot in pairs(data.ItemSlots.slots) do
end
         if slot.startingItem and slot.startingItem ~= "" then
 
             return slot.startingItem
local function get_by_path(tbl, path)
    if not tbl or path == "" then return nil end
    local cur = tbl
     for part in string.gmatch(path, "([^%.]+)") do
        local key, idx = parse_indexed_part(part)
         if key and key ~= "" then
             if type(cur) ~= "table" then return nil end
            local nextCur = cur[key]
            if nextCur == nil then
                nextCur = cur["!type:" .. key]
            end
            cur = nextCur
        end
        if idx then
            if type(cur) ~= "table" then return nil end
            cur = cur[idx]
         end
         end
        if cur == nil then return nil end
     end
     end
   
     return cur
     return nil
end
end


local function format_value(v)
    local okJson, json = pcall(mw.text.jsonEncode, v)
    if okJson and json == "null" then
        return "null"
    end


-- Локальные функции
    if v == nil then return "" end
local findDataById, formatContent, getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector


-- Поиск данных по ID через индекс
    local t = type(v)
findDataById = function(itemDataIndex, id)
     if t == "string" or t == "number" or t == "boolean" then
     if not itemDataIndex then return nil end
        return tostring(v)
for _, item in ipairs(itemDataIndex) do
    elseif t == "table" then
if item.id == id then
        local ok, json2 = pcall(mw.text.jsonEncode, v)
return item
        if ok and json2 then
end
            return json2
end
        end
        return ""
    else
        return tostring(v)
    end
end
 
local function to_nowiki(v)
    return "<nowiki>" .. v .. "</nowiki>"
end
end


-- Форматирование содержимого
local function is_array(tbl)
formatContent = function(content)
    local max = 0
    if type(content) == "table" and not content.id then
    local count = 0
         return "Ошибка: отсутствует id у элемента."
    for k in pairs(tbl) do
        if type(k) ~= "number" then
            return false
        end
         if k > max then max = k end
        count = count + 1
     end
     end
    return count > 0 and max == count
end


    local id = content.id or content
local function deep_copy(src)
   
     local dst = {}
     local amountNumber = 1
     for k, v in pairs(src) do
     if content.amount then
         if type(v) == "table" then
         if type(content.amount) == "table" then
             dst[k] = deep_copy(v)
             amountNumber = content.amount.value or 1
         else
         else
             amountNumber = content.amount
             dst[k] = v
         end
         end
     end
     end
     local amount = (amountNumber and amountNumber ~= 1) and string.format(" [%d]", amountNumber) or ""
     return dst
   
end
    local prob = ""


     if content.weight then
local function deep_merge(dst, src)
         content.prob = content.weight / 100
     for k, v in pairs(src) do
        if type(v) == "table" and type(dst[k]) == "table" then
            deep_merge(dst[k], v)
        elseif type(v) == "table" then
            dst[k] = deep_copy(v)
         else
            dst[k] = v
        end
     end
     end
end


     if content.prob then
local function resolve_entry(data, id)
         prob = string.format(" <div>%s%%</div>", content.prob * 100 >= 1 and math.floor(content.prob * 100) or content.prob * 100)
     if type(data) ~= "table" then
         return nil
     end
     end


     return string.format(
     if id and id ~= "" then
         '{{#invoke:Prototypes/Предмет/Содержание|main|%s|%s%s}}',
        local direct = data[id]
        id, amount, prob
        if direct ~= nil then
    )
            return direct
end
        end
 
        local idsTable = data.id
         if type(idsTable) == "table" then
            local specific = idsTable[id]
            if type(specific) == "table" then
                local base = data["default"]
                if type(base) == "table" then
                    local merged = deep_copy(base)
                    deep_merge(merged, specific)
                    return merged
                end
                return deep_copy(specific)
            end
        end
    end


-- Получение содержимого через таблицу
     local base = data["default"]
getContentsOutput = function(contents)
     if type(base) == "table" then
     local result = ""
         return deep_copy(base)
     for _, content in ipairs(contents) do
         result = result .. formatContent(content)
     end
     end
     return result
     return nil
end
end


-- Обработка вложенных таблиц
local function collect_id_keys(data)
processNestedSelectors = function(children, visited)
    if type(data) ~= "table" then
visited = visited or {}
        return {}
     if not children or #children == 0 then return "" end
     end


     local result = ""
     local idsTable = data.id
    local ids = {}


     for _, child in ipairs(children) do
     if type(idsTable) == "table" then
        if child.id then
        for k in pairs(idsTable) do
if not visited[child.id] then
            ids[#ids + 1] = k
    result = result .. formatContent(child)
end
        elseif child["!type"] == "NestedSelector" then
            result = result .. handleNestedSelector(child, true, visited)
        elseif child["!type"] == "GroupSelector" then
            result = result .. handleGroupSelector(child, visited)
         end
         end
        return ids
     end
     end


     return result
    for k in pairs(data) do
        if k ~= "default" and k ~= "id" then
            ids[#ids + 1] = k
        end
    end
     return ids
end
end


-- Обработка таблиц
local function contains_target(v, target)
getTableOutput = function(tableId, visited)
    if type(v) == "table" then
    visited = visited or {}
        if is_array(v) then
            for _, item in ipairs(v) do
                if tostring(item) == target then
                    return true
                end
            end
            return false
        end


    if visited[tableId] then
        for _, item in pairs(v) do
         return ''
            if tostring(item) == target then
                return true
            end
        end
         return false
     end
     end


     visited[tableId] = true
     return tostring(v) == target
end


     local tableData = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local function is_nonempty_value(v)
     local tableDataIndex = findDataById(tableData, tableId)
     if v == nil then return false end
    if type(v) == "table" then
        return next(v) ~= nil
    end
     return true
end


     if not tableDataIndex then return 'Таблица не найдена.' end
local function find_matching_ids(idsTable, keyPath, searchValue)
     local target = tostring(searchValue)
    local matches = {}


     if tableDataIndex['!type:GroupSelector'] then
     for idKey, entry in pairs(idsTable) do
        return handleGroupSelector(tableDataIndex['!type:GroupSelector'], visited)
        if type(entry) == "table" then
    elseif tableDataIndex['!type:AllSelector'] then
            local v = get_by_path(entry, keyPath)
         return processNestedSelectors(tableDataIndex['!type:AllSelector'].children, visited)
            if v ~= nil and contains_target(v, target) then
                matches[#matches + 1] = idKey
            end
         end
     end
     end


     return 'Таблица не содержит элементов.'
     return matches
end
end


-- Формирование списка содержащихся предметов или таблиц
local function preprocess_or_return(frame, text)
getContainedOutput = function(itemData, id, visited)
    if type(frame.preprocess) == "function" then
     visited = visited or {}
        return frame:preprocess(text)
     end
    return text
end


     if visited[id] then
local function get_field_loose(entry, fieldId)
        return ''
     local value = entry[fieldId]
     end
    if value ~= nil then return value end
    if fieldId == "" then return nil end
 
     local first = string.sub(fieldId, 1, 1)
    local tail = string.sub(fieldId, 2)
    value = entry[string.lower(first) .. tail]
    if value ~= nil then return value end


     visited[id] = true
     return entry[string.upper(first) .. tail]
end


    local item = findDataById(itemData, id)
local function apply_pattern(s, pattern, repl)
     if not item then return '' end
     if not pattern or pattern == "" or not s then
        return s
    end


     local result = {}
     local text = tostring(s)
    local replacement
    if repl and repl ~= "" then
        replacement = tostring(repl)
        replacement = replacement:gsub("\\(%d)", "%%%1")
    else
        replacement = "%1"
    end


     -- Обработка StorageFill
     local patt = pattern
     if item.StorageFill and item.StorageFill.contents then
     if not patt:find("%^") and not patt:find("%$") then
         result[#result + 1] = getContentsOutput(item.StorageFill.contents)
         patt = "^" .. patt .. "$"
    end


     -- Обработка EntityTableContainerFill
     return (text:gsub(patt, replacement))
    elseif item.EntityTableContainerFill and item.EntityTableContainerFill.containers then
end
        local containers = item.EntityTableContainerFill.containers


        -- Обработка entity_storage
local function flatten_parts(entry)
        if containers.entity_storage then
    if type(entry) ~= "table" then return {} end
            -- Если есть просто элементы с id, то форматируем их как обычные предметы
            if containers.entity_storage.children then
                for _, child in ipairs(containers.entity_storage.children) do
                    if child.id then
                        result[#result + 1] = formatContent(child) -- Теперь одиночные id не игнорируются
                    elseif child["!type"] == "GroupSelector" then
                        result[#result + 1] = handleGroupSelector(child, visited)
                    elseif child["!type"] == "AllSelector" then
                        result[#result + 1] = processNestedSelectors(child.children, visited)
                    end
                end
            end


            -- Если есть таблица, то загружаем её
    local parts = {}
            if containers.entity_storage.tableId then
    local function append_table_json(key, value)
                result[#result + 1] = getTableOutput(containers.entity_storage.tableId, visited)
        local ok, json = pcall(mw.text.jsonEncode, value)
            end
        if ok and json then
            parts[#parts + 1] = key .. "=" .. to_nowiki(json)
         end
         end
    end


         -- Обработка storagebase (аналогично entity_storage)
    local function walk(tbl, prefix)
         if containers.storagebase then
        local keys = {}
            if containers.storagebase.children then
         for k in pairs(tbl) do keys[#keys + 1] = k end
                for _, child in ipairs(containers.storagebase.children) do
         table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
                    if child.id then
        for _, k in ipairs(keys) do
                        result[#result + 1] = formatContent(child)
            local v = tbl[k]
                    elseif child["!type"] == "GroupSelector" then
            local kStr = tostring(k)
                        result[#result + 1] = handleGroupSelector(child, visited)
            local key = (prefix == "" and kStr or prefix .. "." .. kStr)
                     elseif child["!type"] == "AllSelector" then
            if type(v) == "table" then
                         result[#result + 1] = processNestedSelectors(child.children, visited)
                if next(v) == nil then
                else
                    append_table_json(key, v)
                     if is_array(v) then
                        local first = v[1]
                        if type(first) == "table" then
                            walk(first, key)
                        end
                    else
                         walk(v, key)
                     end
                     end
                 end
                 end
             end
             else
 
                 parts[#parts + 1] = key .. "=" .. tostring(v)
            if containers.storagebase.tableId then
                 result[#result + 1] = getTableOutput(containers.storagebase.tableId, visited)
             end
             end
         end
         end
     end
     end


     return table.concat(result)
     walk(entry, "")
 
    return parts
end
end


-- Обработка AllSelector
local function flatten_entry(entry)
handleAllSelector = function(allSelector)
    local parts = flatten_parts(entry)
     if not allSelector.children then return '' end
     if #parts == 0 then
     return processNestedSelectors(allSelector.children)
        return ""
    end
     return table.concat(parts, "|")
end
end


-- Обработка GroupSelector
function p.findInGenerator(frame)
handleGroupSelector = function(groupSelector)
     local args = frame.args or {}
     if not groupSelector.children then return '' end
     local searchId = args[1] or ""
     local result = ""
     local kind = (args[2] or ""):lower()
     local wrapperStart, wrapperEnd = "", ""
    local fieldId = args[3] or ""


    -- Проверка для контейнера EntityTableContainerFill
     if searchId == "" or fieldId == "" then
     if groupSelector.weight and groupSelector.weight ~= "default" then
         return ""
        wrapperStart = string.format('{{LinkСard/Сollapsible|name=Группа предметов %s%%|content=', groupSelector.weight)
     end
         wrapperEnd = "}}"
    if kind ~= "prototype" and kind ~= "component" then
     elseif groupSelector["!type"] == "GroupSelector" and not groupSelector.weight then
         return ""
         wrapperStart = '{{LinkСard/Сollapsible|name=Может выпасть лишь один из:|content='
        wrapperEnd = "}}"
     end
     end


     for _, child in ipairs(groupSelector.children) do
     local storeName = (kind == "prototype") and "prototype_store.json" or "component_store.json"
         if child["!type"] == "GroupSelector" then
    local moduleName = get_module_name(storeName)
            result = result .. handleGroupSelector(child)
    local data = load_cached_data(moduleName)
        elseif child["!type"] == "AllSelector" then
    if not data then
            result = result .. string.format('{{LinkСard/Сollapsible|name=Выпадают только вместе:|content=%s}}', handleAllSelector(child))
         return ""
        elseif child.id then
    end
            result = result .. formatContent(child)
 
        else
    local entry = data[searchId]
             result = result .. "<div>Ошибка: отсутствует id у элемента.</div>"
    if type(entry) ~= "table" then
        return ""
    end
 
    local value = get_field_loose(entry, fieldId)
    if value == nil then
        return ""
    end
 
    local out = {}
    local t = type(value)
    if t == "table" then
        for _, v in ipairs(value) do
             out[#out + 1] = v
         end
         end
    else
        out[1] = value
    end
    return mw.text.jsonEncode(out)
end
function p.flattenField(frame)
    local args = frame.args or {}
    local id = args[1] or ""
    local pagePath = args[2] or ""
    if id == "" or pagePath == "" then return "" end
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then return "" end
    local entry = resolve_entry(data, id) or {}
    return flatten_entry(entry)
end
function p.get(frame)
    local args = frame.args or {}
    local id = args[1] or ""
    local pagePath = args[2] or ""
    local keyPath = args[3] or ""
    if pagePath == "" then return "" end
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then return "" end
    local entry = resolve_entry(data, id)
    if entry == nil then return "" end
    if keyPath == "" then
        return format_value(entry)
     end
     end


     return wrapperStart .. result .. wrapperEnd
    local value = get_by_path(entry, keyPath)
     return format_value(value)
end
end


-- Обработка NestedSelector
function p.getId(frame)
handleNestedSelector = function(nestedSelector, wrapped, visited)
    local args = frame.args or {}
visited = visited or {}
     local searchValue = args[1] or ""
     if not nestedSelector.tableId then return '' end
    local pagePath = args[2] or ""
    local keyPath = args[3] or ""
    local searchType = (args.searchType or ""):lower()


     local result = ""
     if searchValue == "" or pagePath == "" or keyPath == "" then
     local classesRolls, classesProb
        return ""
    end
    if searchType == "" then
        searchType = "value"
     end


     if wrapped then
    local moduleName = get_module_name(pagePath)
         if nestedSelector.rolls and nestedSelector.rolls.range then
    local data = load_cached_data(moduleName)
             local rollsResult = processRolls(nestedSelector.rolls)
    if not data then return "[]" end
             if rollsResult and #rollsResult > 0 then
 
                 classesRolls = ', максимум может выпасть: ' .. rollsResult
    local ids = collect_id_keys(data)
     if #ids == 0 then
         return ""
    end
 
    local matches
    if searchType == "key" then
        local target = tostring(searchValue)
        matches = {}
        for _, idKey in ipairs(ids) do
             local entry = resolve_entry(data, idKey)
             if type(entry) == "table" then
                 local v = get_by_path(entry, keyPath)
                if type(v) == "table" and v[target] ~= nil then
                    matches[#matches + 1] = idKey
                end
             end
             end
         end
         end
         if nestedSelector.prob then
    else
             classesProb = string.format(" <div>%s%%</div>", nestedSelector.prob * 100 >= 1 and math.floor(nestedSelector.prob * 100) or nestedSelector.prob * 100)
        local target = tostring(searchValue)
         matches = {}
        for _, idKey in ipairs(ids) do
             local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if v ~= nil and contains_target(v, target) then
                    matches[#matches + 1] = idKey
                end
            end
         end
         end
     end
     end


     if wrapped and (classesRolls or classesProb) then
     if #matches == 0 then
         result = result .. string.format('{{LinkСard/Сollapsible|name=Группа предметов%s%s|content=', classesRolls or "", classesProb or "")
         return ""
    end
 
    local ok, json = pcall(mw.text.jsonEncode, matches)
    if ok and json then
        return json
     end
     end


     result = result .. getTableOutput(nestedSelector.tableId, visited)
     return ""
end
 
function p.getTplId(frame)
    local args = frame.args or {}
    local searchValue = args[1] or ""
    local pagePath = args[2] or ""
    local keyPath = args[3] or ""
    local tplPath = mw.text.unstripNoWiki(args[4] or "")
    local searchType = (args.searchType or ""):lower()


     if wrapped and (classesRolls or classesProb) then
     if searchType == "" then
         result = result .. "}}"
        searchType = "value"
    end
    if searchType == "path" then
        searchValue = ""
        pagePath = args[1] or ""
        keyPath = args[2] or ""
        tplPath = mw.text.unstripNoWiki(args[3] or "")
    end
    if pagePath == "" or keyPath == "" or tplPath == "" then
         return ""
    end
    if searchType ~= "path" and searchValue == "" then
        return ""
     end
     end


     return result
     local moduleName = get_module_name(pagePath)
end
    local data = load_cached_data(moduleName)
    if not data then return "" end


-- Формирование списка химии
     local ids = collect_id_keys(data)
getChemOutput = function(itemData, id)
     if #ids == 0 then
     local item = findDataById(itemData, id)
         return ""
     if not item
      or not item.SolutionContainerManager
      or not item.SolutionContainerManager.solutions then  
         return ''
     end
     end


     -- Сбор всех реагентов
     local matches
     local allReagents = {}
    if searchType == "path" then
    for _, solution in pairs(item.SolutionContainerManager.solutions) do
        matches = {}
        if solution and solution.reagents then
        for _, idKey in ipairs(ids) do
             for _, reagent in ipairs(solution.reagents) do
            local entry = resolve_entry(data, idKey)
                 table.insert(allReagents, reagent)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if is_nonempty_value(v) then
                    matches[#matches + 1] = idKey
                end
            end
        end
     elseif searchType == "key" then
        local target = tostring(searchValue)
        matches = {}
        for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if type(v) == "table" and v[target] ~= nil then
                    matches[#matches + 1] = idKey
                end
             end
        end
    else
        local target = tostring(searchValue)
        matches = {}
        for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                 if v ~= nil and contains_target(v, target) then
                    matches[#matches + 1] = idKey
                end
             end
             end
         end
         end
     end
     end


     -- Если все реагенты — это только Fiber, то не выводим ничего
     if #matches == 0 then
     local hasNonFiber = false
        return ""
     for _, reagent in ipairs(allReagents) do
    end
         if reagent.ReagentId ~= "Fiber" then
 
             hasNonFiber = true
     local out = {}
            break
     for _, idKey in ipairs(matches) do
        local tpl = p.getTpl({ args = { idKey, pagePath, tplPath }, data = data })
         if tpl ~= "" then
             out[#out + 1] = tpl
         end
         end
     end
     end


     if not hasNonFiber then
    if #out == 0 then
         return ''
        return ""
    end
 
    local result = table.concat(out, " ")
    return preprocess_or_return(frame, result)
end
 
function p.getTpl(frame)
    local args = frame.args or {}
    local id = args[1] or ""
    local pagePath = args[2] or ""
    local tplPath = mw.text.unstripNoWiki(args[3] or "")
 
    if id == "" or pagePath == "" or tplPath == "" then
        return ""
    end
 
    local moduleName = get_module_name(pagePath)
    local data = frame.data
     if not data then
        data = load_cached_data(moduleName)
    end
    if not data then
         return ""
    end
 
    local entry = resolve_entry(data, id)
    local extra = flatten_entry(entry)
    local tplStr = "{{" .. tostring(tplPath) .. "|id=" .. tostring(id)
    if extra ~= "" then
        tplStr = tplStr .. "|" .. extra
     end
     end
    tplStr = tplStr .. "}}"
    return preprocess_or_return(frame, tplStr)
end
function p.getTplGenerator(frame)
    local args = frame.args or {}
    local searchId = args[1] or ""
    local kind = (args[2] or ""):lower()
    local generatorId = args[3] or ""
    local tplPath = mw.text.unstripNoWiki(args[4] or "")


     local function processSolution(solution)
     if searchId == "" or generatorId == "" or tplPath == "" then
         local output = ""
         return ""
        if solution and solution.reagents then
    end
            for _, reagent in ipairs(solution.reagents) do
    if kind ~= "prototype" and kind ~= "component" then
                local chemInfo = chemTranslateData[reagent.ReagentId]
        return ""
                local displayName = chemInfo and chemInfo.name or reagent.ReagentId
    end
                output = output .. string.format(
 
                    '<li>[[Химия#chem_%s|%s]] (%d ед.)</li>',
    local dir = (kind == "prototype") and "prototype/" or "component/"
                    reagent.ReagentId, displayName, reagent.Quantity
    local pagePath = dir .. generatorId .. ".json"
                )
 
             end
    local idsJson = p.findInGenerator({ args = { searchId, kind, generatorId } })
    local ok, ids = pcall(mw.text.jsonDecode, idsJson or "")
    if not ok or type(ids) ~= "table" or #ids == 0 then
        return ""
    end
 
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then
        return ""
    end
 
    local out = {}
    for _, id in ipairs(ids) do
        local tpl = p.getTpl({ args = { id, pagePath, tplPath }, data = data })
        if tpl ~= "" then
             out[#out + 1] = tpl
         end
         end
        return output
     end
     end


     local result = ""
     local result = table.concat(out, " ")
    result = result .. processSolution(item.SolutionContainerManager.solutions["drink"])
     return preprocess_or_return(frame, result)
     result = result .. processSolution(item.SolutionContainerManager.solutions["food"])
end
   
    result = result .. processSolution(item.SolutionContainerManager.solutions["beaker"])
    result = result .. processSolution(item.SolutionContainerManager.solutions["injector"])
   
    result = result .. processSolution(item.SolutionContainerManager.solutions["pen"])


     return result ~= "" and string.format('<ul class="1">%s</ul>', result) or ''
function p.flattenParams(entry)
     return flatten_parts(entry)
end
end


-- Функция поиска count в itemStackData
function p.getGenerator(frame)
local function getStackCount(id)
     local args = frame.args or {}
     local item = findDataById(itemStackData, id)
    local searchId = args[1] or ""
     if item and item.Stack and item.Stack.count then
    local kind = (args[2] or ""):lower()
         return item.Stack.count
    local generatorId = args[3] or ""
 
     if searchId == "" or generatorId == "" then
         return ""
     end
     end
     return nil
     if kind ~= "prototype" and kind ~= "component" then
        return ""
    end
 
    local idsJson = p.findInGenerator({ args = { searchId, kind, generatorId } })
    local ok, ids = pcall(mw.text.jsonDecode, idsJson or "")
    if not ok or type(ids) ~= "table" or #ids == 0 then
        return ""
    end
 
    local okOut, outJson = pcall(mw.text.jsonEncode, ids)
    if okOut and outJson then
        return outJson
    end
 
    return ""
end
end


-- Основная функция модуля
function p.hasComp(frame)
function p.main(frame)
     local args = frame.args or {}
     local mode = frame.args[1]
    local entityId = args[1] or ""
     local id = frame.args[2]
     local compName = args[2] or ""
 
    if entityId == "" or compName == "" then
        return "false"
    end
 
    local moduleName = get_module_name("component.json")
    local data = load_cached_data(moduleName)
    if not data then
        return "false"
    end


     if not id then return 'Не указан ID.' end
     if type(data) ~= "table" then
   
        return "false"
     local itemDataIndex = itemData
     end
   
    if not itemData then return 'Не удалось загрузить данные.' end


     if mode == 'framing' then
    local entry = data[entityId]
         local subMode = frame.args[2]
     if type(entry) ~= "table" then
        local id = frame.args[3]
         return "false"
    end


         if not id then
    local target = tostring(compName)
             return 'Не указан ID для режима framing.'
    for _, v in ipairs(entry) do
         if tostring(v) == target then
             return "true"
         end
         end
    end


        if subMode == 'chem' then
    return "false"
            return frame:preprocess('{{СollapsibleMenu|color=#3e7c82|' .. getChemOutput(chemData, id) .. '}}')
end
        elseif subMode == 'contained' then
 
            return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(itemDataIndex, id) .. '}}')
function p.GeneratorId(frame)
        elseif subMode == "slot" then
    local args = frame.args or {}
            local itemDataEntry = findDataById(itemSlotsData, id)
    local pagePath = args[1] or ""
            if not itemDataEntry then return "" end
    local replace = mw.text.unstripNoWiki(args.replace or "")
            local startingItem = getFirstStartingItem(itemDataEntry)
    local pattern = mw.text.unstripNoWiki(args.pattern or "(.*)")
            if not startingItem then return "" end
 
            return frame:preprocess('{{СollapsibleMenu|color=#71702a|' .. formatContent(startingItem) .. '}}')
    if pagePath == "" then
        elseif subMode == "stack" then
        return ""
             local count = getStackCount(id)
    end
             return count and '(' .. count .. ')' or ""
 
         else
    local moduleName = get_module_name(pagePath)
             return 'Неизвестный подрежим для framing: ' .. subMode
    local data = load_cached_data(moduleName)
    if not data then
        return ""
    end
 
    local idsTable = data.id
    if type(idsTable) ~= "table" then
        return ""
    end
 
    local ids = {}
    for k in pairs(idsTable) do
        ids[#ids + 1] = k
    end
 
    table.sort(ids)
 
    if replace ~= "" then
        local out = {}
        for _, id in ipairs(ids) do
             local text = apply_pattern(id, pattern, replace)
             if text ~= "" then
                out[#out + 1] = text
            end
        end
         if #out == 0 then
             return ""
         end
         end
     elseif mode == 'stack' then
        return preprocess_or_return(frame, table.concat(out, "\n"))
        local count = getStackCount(id)
     end
         return count or ""
 
    elseif mode == 'chem' then
    local ok, json = pcall(mw.text.jsonEncode, ids)
        return getChemOutput(chemData, id)
    if ok and json then
     elseif mode == 'contained' then
         return json
        return frame:preprocess(getContainedOutput(itemDataIndex, id))
    end
     elseif mode == "slot" then
 
         local itemDataEntry = findDataById(itemSlotsData, id)
    return ""
        if not itemDataEntry then return "" end
end
        local startingItem = getFirstStartingItem(itemDataEntry)
 
         if not startingItem then return "" end
function p.GeneratorTplId(frame)
        return frame:preprocess(formatContent(startingItem))
     local args = frame.args or {}
     elseif mode == 'rolls' then
    local pagePath = args[1] or ""
         local entity = findDataById(itemDataIndex, id)
    local tplPath = args[2] or ""
         if not entity then return 'ID не найден в данных.' end
 
        if entity.EntityTableContainerFill then
     if pagePath == "" or tplPath == "" then
             local containers = entity.EntityTableContainerFill.containers
         return ""
            if containers.entity_storage and containers.entity_storage.rolls then
    end
                return processRolls(containers.entity_storage.rolls)
 
            end
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then
        return ""
    end
 
    local idsTable = data.id
    if type(idsTable) ~= "table" then
         return ""
    end
 
     local out = {}
 
    for idKey in pairs(idsTable) do
         local tpl = p.getTpl({ args = { idKey, pagePath, tplPath }, data = data })
         if tpl ~= "" then
             out[#out + 1] = tpl
         end
         end
        return ''
    else
        return 'Неизвестный режим: ' .. mode
     end
     end
    table.sort(out)
    local result = table.concat(out, " ")
    return preprocess_or_return(frame, result)
end
end


return p
return p