Модуль:Prototypes/Машина/Станок: различия между версиями

Материал из Space Station 14 Вики
мНет описания правки
мНет описания правки
(не показаны 23 промежуточные версии этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}


-- Функция для загрузки данных станков
-----------------------------------------------------------
local function loadLatheData()
-- Загрузка данных
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe.json"):getContent())
-----------------------------------------------------------
end
local latheData      = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local recipeData    = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local recipePackData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipe pack.json/data")
local researchData  = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local materialData  = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local chemData      = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
 
-----------------------------------------------------------
-- Вспомогательные функции
-----------------------------------------------------------
local function sortRecipesByPriority(recipes)
    table.sort(recipes, function(a, b)
        local priority = { Static = 1, EMAG = 3 }
        local aPriority = priority[a.discipline] or 2
        local bPriority = priority[b.discipline] or 2
 
        if a.isEmag ~= b.isEmag then
            return not a.isEmag
        end
 
        if aPriority == bPriority then
            if a.tier == b.tier then
                return a.discipline < b.discipline
            end
            return a.tier < b.tier
        end


-- Функция для загрузки данных рецептов
        return aPriority < bPriority
local function loadRecipeData()
    end)
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe/recipes.json"):getContent())
end
end


-- Функция для загрузки данных исследований
local function getRecipeDetails(recipeId)
local function loadResearchData()
    for _, recipe in ipairs(recipeData) do
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/research.json"):getContent())
        if recipe.id == recipeId then
            return recipe
        end
    end
    return nil
end
end


-- Функция для загрузки данных материалов
local function findInResearch(recipeId)
local function loadMaterialData()
    for _, research in ipairs(researchData) do
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/materials.json"):getContent())
        if research and research.recipeUnlocks then
            for _, unlock in ipairs(research.recipeUnlocks) do
                if unlock == recipeId then
                    return {
                        name = research.name,
                        tier = research.tier,
                        discipline = research.discipline
                    }
                end
            end
        end
    end
    return nil
end
end


-- Функция для загрузки данных химических веществ
local function getRecipePackDetails(packId)
local function loadChemData()
    for _, pack in ipairs(recipePackData) do
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/chem prototypes.json"):getContent())
        if pack.id == packId then
            return pack
        end
    end
    return nil
end
end


-- Функция для форматирования времени
-----------------------------------------------------------
local function format_seconds_to_short_string(input_seconds)
-- Функция для сбора рецептов из станка
local minutes = math.floor(input_seconds / 60)
-----------------------------------------------------------
local seconds = input_seconds % 60
local function getLatheRecipes(lathe)
    local recipes = {}
    local chemMapping = {}
    for id, chem in pairs(chemData) do
        chemMapping[id] = chem.name
    end


local minutes_part = minutes > 0 and (minutes .. " мин.") or nil
    -- Вспомогательная функция для обработки одного рецепта
local seconds_part = seconds > 0 and (seconds .. " сек.") or nil
    local function processRecipe(recipeId, defaultDiscipline, isEmag)
        local recipe = getRecipeDetails(recipeId)
        if recipe then
            if recipe.result then
                local info = {
                    id = recipe.id,
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = defaultDiscipline,
                    tier = 0,
                    isEmag = isEmag or false
                }
                if defaultDiscipline ~= "Static" then
                    local researchInfo = findInResearch(recipeId)
                    if researchInfo then
                        info.discipline = researchInfo.discipline
                        info.tier = researchInfo.tier
                        info.researchName = researchInfo.name
                    end
                end
                table.insert(recipes, info)
            elseif recipe.resultReagents then
                for reagent, amount in pairs(recipe.resultReagents) do
                    local reagentName = chemMapping[reagent] or reagent
                    table.insert(recipes, {
                        id = recipe.id,
                        result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = defaultDiscipline,
                        tier = 0,
                        isEmag = isEmag or false
                    })
                    break
                end
            end
        end
    end


if minutes_part and seconds_part then
    -- Обработка рецептов для lathe.Lathe (старый и новый формат)
return minutes_part .. " " .. seconds_part
    if lathe.Lathe then
elseif seconds_part then
        if lathe.Lathe.staticRecipes then
return seconds_part
            for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
elseif minutes_part then
                processRecipe(recipeId, "Static", false)
return minutes_part
            end
else
        end
return '0 сек.'
        if lathe.Lathe.dynamicRecipes then
end
            for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
end
                processRecipe(recipeId, "Dynamic", false)
 
            end
-- Функция для сортировки рецептов
        end
local function sortRecipesByPriority(recipes)
        if lathe.Lathe.staticPacks then
table.sort(recipes, function(a, b)
            for _, packId in ipairs(lathe.Lathe.staticPacks) do
local priority = { Static = 1, EMAG = 3 }
                local pack = getRecipePackDetails(packId)
local aPriority = priority[a.discipline] or 2
                if pack and pack.recipes then
local bPriority = priority[b.discipline] or 2
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Static", false)
                    end
                end
            end
        end
        if lathe.Lathe.dynamicPacks then
            for _, packId in ipairs(lathe.Lathe.dynamicPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Dynamic", false)
                    end
                end
            end
        end
    end


if a.isEmag ~= b.isEmag then
    if lathe.EmagLatheRecipes then
return not a.isEmag
        if lathe.EmagLatheRecipes.emagStaticRecipes then
end
            for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
                processRecipe(recipeId, "Static", true)
            end
        end
        if lathe.EmagLatheRecipes.emagDynamicRecipes then
            for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
                processRecipe(recipeId, "Dynamic", true)
            end
        end
        if lathe.EmagLatheRecipes.emagStaticPacks then
            for _, packId in ipairs(lathe.EmagLatheRecipes.emagStaticPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Static", true)
                    end
                end
            end
        end
        if lathe.EmagLatheRecipes.emagDynamicPacks then
            for _, packId in ipairs(lathe.EmagLatheRecipes.emagDynamicPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Dynamic", true)
                    end
                end
            end
        end
    end


if aPriority == bPriority then
    sortRecipesByPriority(recipes)
if a.tier == b.tier then
    return recipes
return a.discipline < b.discipline
end
end
return a.tier < b.tier
end


return aPriority < bPriority
-----------------------------------------------------------
end)
-- Общие таблицы для форматирования вывода
-----------------------------------------------------------
local disciplineMapping = {
    Arsenal = "Арсенал",
    Industrial = "Промышленность",
    Experimental = "Экспериментальное",
    CivilianServices = "Обслуживание персонала"
}
local tierColors = {
    [1] = "#54d554",
    [2] = "#ed9000",
    [3] = "#d72a2a"
}
local materialMappingGlobal = {}
for _, material in ipairs(materialData) do
    if material.id then
        materialMappingGlobal[material.id] = material.stackEntity or material.id or material.name
    end
end
end


function p.main(frame)
-----------------------------------------------------------
-- Подключение CSS
-- Функция для формирования строки рецепта
local cssLink = frame:extensionTag('templatestyles', '', {
-----------------------------------------------------------
src = 'Шаблон:Prototypes/Машина/Станок/styles.css'
local function formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
})
    local out = ""
    local scaledTime = recipe.completetime * timeMultiplier
    out = out .. '{{Шаблон:Prototypes/Машина/Станок/base|product=' .. recipe.result
    out = out .. '|complete-time={{#invoke:Code/Формат/Время|main|seconds|' .. scaledTime .. '}}|materials='


local latheId = frame.args[1] or ""
    if recipe.materials then
if latheId == "" then
        local materialEntries = {}
return '<div style="color:red;">Не указан ID станка.</div>'
        for material, amount in pairs(recipe.materials) do
end
            local stackEntity = materialMappingGlobal[material] or material
            local scaledAmount = (amount * materialUseMultiplier) / 100
            table.insert(materialEntries, string.format('<b>[[File:%s.png|32x32px|link=]] %g {{#invoke:Entity Lookup|getname|%s}}</b>', stackEntity, scaledAmount, stackEntity))
        end
        out = out .. table.concat(materialEntries)
    else
        out = out .. 'Нет данных о материалах'
    end


local latheData = loadLatheData()
    if recipe.discipline ~= "Static" then
local recipeData = loadRecipeData()
        local tierColor = tierColors[recipe.tier] or "#FFFFFF"
local researchData = loadResearchData()
        local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"
local materialData = loadMaterialData()
        out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
local chemData = loadChemData()
        out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
    end


local lathe = nil
    if recipe.isEmag then
for _, data in ipairs(latheData) do
        out = out .. '|mode-emag=1'
if data.id == latheId then
    end
lathe = data
break
end
end


if not lathe then
    if recipe.discipline ~= "Static" then
return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
        out = out .. '|mode-research=1'
end
    end


local materialMapping = {}
    out = out .. '}}'
for _, material in ipairs(materialData) do
    return out
materialMapping[material.material.id] = material.material.stackEntity
end
end


local chemMapping = {}
-----------------------------------------------------------
for id, chem in pairs(chemData) do
-- Функция для поиска и вывода рецептов по ID станка
chemMapping[id] = chem.name
-----------------------------------------------------------
end
function p.lathe(frame)
    local latheId = frame.args[1] or ""
    if latheId == "" then
        return '<div style="color:red;">Не указан ID станка.</div>'
    end


local out = cssLink
    local lathe = nil
local recipes = {}
    for _, data in ipairs(latheData) do
        if data.id == latheId then
            lathe = data
            break
        end
    end


local function getRecipeDetails(recipeId)
    if not lathe then
for _, recipe in ipairs(recipeData) do
        return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
if recipe.id == recipeId then
    end
return recipe.latheRecipe
end
end
return nil
end


local function findInResearch(recipeId)
    local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
for _, research in ipairs(researchData) do
    local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
if research.technology and research.technology.recipeUnlocks then
    local recipes = getLatheRecipes(lathe)
for _, unlock in ipairs(research.technology.recipeUnlocks) do
    local out = ""
if unlock == recipeId then
    for _, recipe in ipairs(recipes) do
return {
        out = out .. formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
name = research.technology.name,
    end
tier = research.technology.tier,
discipline = research.technology.discipline
}
end
end
end
end
return nil
end


-- Обработка staticRecipes
    return mw.getCurrentFrame():preprocess(out)
if lathe.Lathe.staticRecipes then
end
for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
local recipe = getRecipeDetails(recipeId)
if recipe and recipe.result then
table.insert(recipes, {
result = recipe.result,
completetime = recipe.completetime,
materials = recipe.materials,
discipline = "Static",
tier = 0
})
elseif recipe and recipe.resultReagents then
for reagent, amount in pairs(recipe.resultReagents) do
if type(reagent) == "string" and reagent ~= "category" then
local reagentName = chemMapping[reagent] or reagent
table.insert(recipes, {
result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
completetime = recipe.completetime,
materials = recipe.materials,
discipline = "Static",
tier = 0
})
break
end
end
else
out = out .. '<div style="color:red;">Ошибка: Рецепт с ID "' .. recipeId .. '" не найден или поля result/resultReagents отсутствуют.</div>'
end
end
end


-- Обработка dynamicRecipes
-----------------------------------------------------------
if lathe.Lathe.dynamicRecipes then
-- Функция для поиска и вывода рецептов по ID предмета
for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
-----------------------------------------------------------
local recipe = getRecipeDetails(recipeId)
function p.item(frame)
if recipe then
    local itemId = frame.args[1] or ""
local researchInfo = findInResearch(recipeId)
    if itemId == "" then
if researchInfo then
        return '<div style="color:red;">Не указан ID предмета.</div>'
table.insert(recipes, {
    end
result = recipe.result,
completetime = recipe.completetime,
materials = recipe.materials,
discipline = researchInfo.discipline,
tier = researchInfo.tier,
researchName = researchInfo.name
})
end
end
end
end


-- Обработка emagStaticRecipes
    local recipesOutput = ""
if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
    local foundAny = false
for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
local recipe = getRecipeDetails(recipeId)
if recipe then
table.insert(recipes, {
result = recipe.result,
completetime = recipe.completetime,
materials = recipe.materials,
discipline = "Static",
tier = 0,
isEmag = true
})
end
end
end


-- Обработка emagDynamicRecipes
    for _, lathe in ipairs(latheData) do
if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicRecipes then
        local recipes = getLatheRecipes(lathe)
for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
        local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
local recipe = getRecipeDetails(recipeId)
        local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
if recipe then
local researchInfo = findInResearch(recipeId)
if researchInfo then
table.insert(recipes, {
result = recipe.result,
completetime = recipe.completetime,
materials = recipe.materials,
discipline = researchInfo.discipline,
tier = researchInfo.tier,
researchName = researchInfo.name,
isEmag = true
})
end
end
end
end


sortRecipesByPriority(recipes)
        for _, recipe in ipairs(recipes) do
            if recipe.id == itemId or recipe.result == itemId then
                foundAny = true
                local recipeStr = formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
                recipeStr = recipeStr:gsub("}}$", "|method-container=" .. lathe.id .. "}}")
                recipesOutput = recipesOutput .. recipeStr
            end
        end
    end


-- Таблица для перевода названий дисциплин
    if not foundAny then
local disciplineMapping = {
        return '<div style="color:red;">Рецепт для предмета с ID "' .. itemId .. '" не найден во всех станках.</div>'
Arsenal = "Арсенал",
    end
Industrial = "Промышленность",
Experimental = "Экспериментальное",
CivilianServices = "Обслуживание персонала"
}


-- Таблица для цветов по уровням
    local out = '<div class="grid-item-compressed">' .. recipesOutput .. '</div>'
local tierColors = {
    return mw.getCurrentFrame():preprocess(out)
[1] = "#54d554",
end
[2] = "#ed9000",
[3] = "#d72a2a"
}


local materialUseMultiplier = lathe.Lathe.materialUseMultiplier or 1
-----------------------------------------------------------
local timeMultiplier = lathe.Lathe.timeMultiplier or 1
-- Функция для поиска и вывода рецептов по ID материала
-----------------------------------------------------------
function p.material(frame)
    local materialId = frame.args[1] or ""
    if materialId == "" then
        return '<div style="color:red;">Не указан ID материала.</div>'
    end


for _, recipe in ipairs(recipes) do
    local recipesOutput = ""
local scaledTime = format_seconds_to_short_string(recipe.completetime * timeMultiplier)
    local foundAny = false
out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
out = out .. '|complete-time=' .. scaledTime
out = out .. '|materials='


if next(recipe.materials) then
    for _, lathe in ipairs(latheData) do
for material, amount in pairs(recipe.materials) do
        local recipes = getLatheRecipes(lathe)
local stackEntity = materialMapping[material] or material
        local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
local scaledAmount = (amount * materialUseMultiplier) / 100
        local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
out = out .. '<b>[[File:' .. stackEntity .. '.png|32x32px|link=]] ' .. scaledAmount .. ' {{#invoke:Entity Lookup|getname|' .. stackEntity .. '}}</b>'
end
else
out = out .. 'Нет данных о материалах'
end


-- Информация об исследовании
        for _, recipe in ipairs(recipes) do
if recipe.discipline ~= "Static" then
            if recipe.materials then
local tierColor = tierColors[recipe.tier] or "#FFFFFF"
                for matId, _ in pairs(recipe.materials) do
local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"
                    if matId == materialId then
                        foundAny = true
                        local recipeStr = formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
                        recipeStr = recipeStr:gsub("}}$", "|method-container=" .. lathe.id .. "}}")
                        recipesOutput = recipesOutput .. recipeStr
                        break
                    end
                end
            end
        end
    end


out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
    if not foundAny then
out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
        return '<div style="color:red;">Для материала с ID "' .. materialId .. '" рецептов не найдено во всех станках.</div>'
end
    end


-- Пометка при взломе EMAG
    local out = '<div class="grid-item-compressed">' .. recipesOutput .. '</div>'
if recipe.isEmag then
    return mw.getCurrentFrame():preprocess(out)
out = out .. '|mode-emag=1'
end
end


-- Пометка для исследуемой технологии
-----------------------------------------------------------
if recipe.discipline ~= "Static" then
-- Функция для универсального вызова из шаблона
out = out .. '|mode-research=1'
-----------------------------------------------------------
end
function p.main(frame)
 
    local arguments = require("Модуль:Arguments").getArgs(frame, { unwrap = true })
out = out .. '}}'
    local mode = arguments[1] or ""
end
    local id  = arguments[2] or ""
 
   
return mw.getCurrentFrame():preprocess(out)
    -- Для обеспечения работы mw.getCurrentFrame(), переиспользуем исходный frame
    local newFrame = {
        args = { id },
        getCurrentFrame = frame.getCurrentFrame or function() return frame end
    }
   
    if mode == "lathe" then
        return p.lathe(newFrame)
    elseif mode == "item" then
        return p.item(newFrame)
    elseif mode == "material" then
        return p.material(newFrame)
    else
        return '<div style="color:red;">Неверный режим вызова: "' .. mode .. '". Используйте "lathe", "item" или "material".</div>'
    end
end
end


return p
return p

Версия от 04:21, 15 апреля 2025

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

local p = {}

-----------------------------------------------------------
-- Загрузка данных
-----------------------------------------------------------
local latheData      = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local recipeData     = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local recipePackData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipe pack.json/data")
local researchData   = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local materialData   = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local chemData       = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")

-----------------------------------------------------------
-- Вспомогательные функции
-----------------------------------------------------------
local function sortRecipesByPriority(recipes)
    table.sort(recipes, function(a, b)
        local priority = { Static = 1, EMAG = 3 }
        local aPriority = priority[a.discipline] or 2
        local bPriority = priority[b.discipline] or 2

        if a.isEmag ~= b.isEmag then
            return not a.isEmag
        end

        if aPriority == bPriority then
            if a.tier == b.tier then
                return a.discipline < b.discipline
            end
            return a.tier < b.tier
        end

        return aPriority < bPriority
    end)
end

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

local function findInResearch(recipeId)
    for _, research in ipairs(researchData) do
        if research and research.recipeUnlocks then
            for _, unlock in ipairs(research.recipeUnlocks) do
                if unlock == recipeId then
                    return {
                        name = research.name,
                        tier = research.tier,
                        discipline = research.discipline
                    }
                end
            end
        end
    end
    return nil
end

local function getRecipePackDetails(packId)
    for _, pack in ipairs(recipePackData) do
        if pack.id == packId then
            return pack
        end
    end
    return nil
end

-----------------------------------------------------------
-- Функция для сбора рецептов из станка
-----------------------------------------------------------
local function getLatheRecipes(lathe)
    local recipes = {}
    local chemMapping = {}
    for id, chem in pairs(chemData) do
        chemMapping[id] = chem.name
    end

    -- Вспомогательная функция для обработки одного рецепта
    local function processRecipe(recipeId, defaultDiscipline, isEmag)
        local recipe = getRecipeDetails(recipeId)
        if recipe then
            if recipe.result then
                local info = {
                    id = recipe.id,
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = defaultDiscipline,
                    tier = 0,
                    isEmag = isEmag or false
                }
                if defaultDiscipline ~= "Static" then
                    local researchInfo = findInResearch(recipeId)
                    if researchInfo then
                        info.discipline = researchInfo.discipline
                        info.tier = researchInfo.tier
                        info.researchName = researchInfo.name
                    end
                end
                table.insert(recipes, info)
            elseif recipe.resultReagents then
                for reagent, amount in pairs(recipe.resultReagents) do
                    local reagentName = chemMapping[reagent] or reagent
                    table.insert(recipes, {
                        id = recipe.id,
                        result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = defaultDiscipline,
                        tier = 0,
                        isEmag = isEmag or false
                    })
                    break
                end
            end
        end
    end

    -- Обработка рецептов для lathe.Lathe (старый и новый формат)
    if lathe.Lathe then
        if lathe.Lathe.staticRecipes then
            for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
                processRecipe(recipeId, "Static", false)
            end
        end
        if lathe.Lathe.dynamicRecipes then
            for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
                processRecipe(recipeId, "Dynamic", false)
            end
        end
        if lathe.Lathe.staticPacks then
            for _, packId in ipairs(lathe.Lathe.staticPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Static", false)
                    end
                end
            end
        end
        if lathe.Lathe.dynamicPacks then
            for _, packId in ipairs(lathe.Lathe.dynamicPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Dynamic", false)
                    end
                end
            end
        end
    end

    if lathe.EmagLatheRecipes then
        if lathe.EmagLatheRecipes.emagStaticRecipes then
            for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
                processRecipe(recipeId, "Static", true)
            end
        end
        if lathe.EmagLatheRecipes.emagDynamicRecipes then
            for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
                processRecipe(recipeId, "Dynamic", true)
            end
        end
        if lathe.EmagLatheRecipes.emagStaticPacks then
            for _, packId in ipairs(lathe.EmagLatheRecipes.emagStaticPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Static", true)
                    end
                end
            end
        end
        if lathe.EmagLatheRecipes.emagDynamicPacks then
            for _, packId in ipairs(lathe.EmagLatheRecipes.emagDynamicPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                    for _, recipeId in ipairs(packRecipes) do
                        processRecipe(recipeId, "Dynamic", true)
                    end
                end
            end
        end
    end

    sortRecipesByPriority(recipes)
    return recipes
end

-----------------------------------------------------------
-- Общие таблицы для форматирования вывода
-----------------------------------------------------------
local disciplineMapping = {
    Arsenal = "Арсенал",
    Industrial = "Промышленность",
    Experimental = "Экспериментальное",
    CivilianServices = "Обслуживание персонала"
}
local tierColors = {
    [1] = "#54d554",
    [2] = "#ed9000",
    [3] = "#d72a2a"
}
local materialMappingGlobal = {}
for _, material in ipairs(materialData) do
    if material.id then
        materialMappingGlobal[material.id] = material.stackEntity or material.id or material.name
    end
end

-----------------------------------------------------------
-- Функция для формирования строки рецепта
-----------------------------------------------------------
local function formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
    local out = ""
    local scaledTime = recipe.completetime * timeMultiplier
    out = out .. '{{Шаблон:Prototypes/Машина/Станок/base|product=' .. recipe.result
    out = out .. '|complete-time={{#invoke:Code/Формат/Время|main|seconds|' .. scaledTime .. '}}|materials='

    if recipe.materials then
        local materialEntries = {}
        for material, amount in pairs(recipe.materials) do
            local stackEntity = materialMappingGlobal[material] or material
            local scaledAmount = (amount * materialUseMultiplier) / 100
            table.insert(materialEntries, string.format('<b>[[File:%s.png|32x32px|link=]] %g {{#invoke:Entity Lookup|getname|%s}}</b>', stackEntity, scaledAmount, stackEntity))
        end
        out = out .. table.concat(materialEntries)
    else
        out = out .. 'Нет данных о материалах'
    end

    if recipe.discipline ~= "Static" then
        local tierColor = tierColors[recipe.tier] or "#FFFFFF"
        local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"
        out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
        out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
    end

    if recipe.isEmag then
        out = out .. '|mode-emag=1'
    end

    if recipe.discipline ~= "Static" then
        out = out .. '|mode-research=1'
    end

    out = out .. '}}'
    return out
end

-----------------------------------------------------------
-- Функция для поиска и вывода рецептов по ID станка 
-----------------------------------------------------------
function p.lathe(frame)
    local latheId = frame.args[1] or ""
    if latheId == "" then
        return '<div style="color:red;">Не указан ID станка.</div>'
    end

    local lathe = nil
    for _, data in ipairs(latheData) do
        if data.id == latheId then
            lathe = data
            break
        end
    end

    if not lathe then
        return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
    end

    local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
    local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
    local recipes = getLatheRecipes(lathe)
    local out = ""
    for _, recipe in ipairs(recipes) do
        out = out .. formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
    end

    return mw.getCurrentFrame():preprocess(out)
end

-----------------------------------------------------------
-- Функция для поиска и вывода рецептов по ID предмета 
-----------------------------------------------------------
function p.item(frame)
    local itemId = frame.args[1] or ""
    if itemId == "" then
        return '<div style="color:red;">Не указан ID предмета.</div>'
    end

    local recipesOutput = ""
    local foundAny = false

    for _, lathe in ipairs(latheData) do
        local recipes = getLatheRecipes(lathe)
        local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
        local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1

        for _, recipe in ipairs(recipes) do
            if recipe.id == itemId or recipe.result == itemId then
                foundAny = true
                local recipeStr = formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
                recipeStr = recipeStr:gsub("}}$", "|method-container=" .. lathe.id .. "}}")
                recipesOutput = recipesOutput .. recipeStr
            end
        end
    end

    if not foundAny then
        return '<div style="color:red;">Рецепт для предмета с ID "' .. itemId .. '" не найден во всех станках.</div>'
    end

    local out = '<div class="grid-item-compressed">' .. recipesOutput .. '</div>'
    return mw.getCurrentFrame():preprocess(out)
end

-----------------------------------------------------------
-- Функция для поиска и вывода рецептов по ID материала
-----------------------------------------------------------
function p.material(frame)
    local materialId = frame.args[1] or ""
    if materialId == "" then
        return '<div style="color:red;">Не указан ID материала.</div>'
    end

    local recipesOutput = ""
    local foundAny = false

    for _, lathe in ipairs(latheData) do
        local recipes = getLatheRecipes(lathe)
        local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
        local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1

        for _, recipe in ipairs(recipes) do
            if recipe.materials then
                for matId, _ in pairs(recipe.materials) do
                    if matId == materialId then
                        foundAny = true
                        local recipeStr = formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
                        recipeStr = recipeStr:gsub("}}$", "|method-container=" .. lathe.id .. "}}")
                        recipesOutput = recipesOutput .. recipeStr
                        break
                    end
                end
            end
        end
    end

    if not foundAny then
        return '<div style="color:red;">Для материала с ID "' .. materialId .. '" рецептов не найдено во всех станках.</div>'
    end

    local out = '<div class="grid-item-compressed">' .. recipesOutput .. '</div>'
    return mw.getCurrentFrame():preprocess(out)
end

-----------------------------------------------------------
-- Функция для универсального вызова из шаблона
-----------------------------------------------------------
function p.main(frame)
    local arguments = require("Модуль:Arguments").getArgs(frame, { unwrap = true })
    local mode = arguments[1] or ""
    local id   = arguments[2] or ""
    
    -- Для обеспечения работы mw.getCurrentFrame(), переиспользуем исходный frame
    local newFrame = {
        args = { id },
        getCurrentFrame = frame.getCurrentFrame or function() return frame end
    }
    
    if mode == "lathe" then
        return p.lathe(newFrame)
    elseif mode == "item" then
        return p.item(newFrame)
    elseif mode == "material" then
        return p.material(newFrame)
    else
        return '<div style="color:red;">Неверный режим вызова: "' .. mode .. '". Используйте "lathe", "item" или "material".</div>'
    end
end

return p