Модуль:Chemistry Lookup: различия между версиями

Материал из FIRE STATION WIKI
Нет описания правки
Метка: отменено
Нет описания правки
 
(не показано 15 промежуточных версий этого же участника)
Строка 1: Строка 1:
local loader = require("Module:JsonPageLoader")
local prototypes = mw.loadData("Module:Chemistry Lookup/data")
 
-- Загружаем данные из JSON файлов
local chem_data = loader.load("User:FireBot/chem_prototypes.json")
local react_data = loader.load("User:FireBot/react_prototypes.json")
local status_data = loader.load("User:FireBot/chem_status.json")


local p = {}
local p = {}
p.chem = prototypes.chem or {}
p.react = prototypes.react or {}
p.status = prototypes.status or {}
p.groupDirection = prototypes.groupDirection or {}


-- Основные данные
-- ===== Хелперы =====
p.chem = chem_data
local function tablelength(T)
p.react = react_data
local count = 0
p.status = status_data
for _ in pairs(T or {}) do count = count + 1 end
return count
end


-- Направления групп для навигации
local function hchangelist(l, frame)
p.groupDirection = {
local out = ""
    Drinks = "Drinks",
local len = tablelength(l)
    Foods = "Cooking",
local i = 0
}
for k, v in pairs(l) do
i = i + 1
if len == i and i ~= 1 then
out = out .. ", and "
elseif i ~= 1 then
out = out .. ", "
end
out = out .. frame:expandTemplate{ title = "HealthModifier", args = { adj = v, kind = k } }
end
return out
end


-- Функция для чтения скалярного значения из химических данных
function p.readscalar(frame)
function p.readscalar(frame)
    local chem_id = frame.args[1]
local a, b = frame.args[1], frame.args[2]
    local property = frame.args[2]
if not (a and b) or not p.chem[a] then return "" end
   
local v = p.chem[a][b]
    if p.chem[chem_id] and p.chem[chem_id][property] then
if v == nil then return "" end
        return mw.text.nowiki(tostring(p.chem[chem_id][property]))
return mw.text.nowiki(tostring(v))
    end
    return ""
end
end


-- Функция для чтения скалярного значения из данных реакций
function p.readscalarreact(frame)
function p.readscalarreact(frame)
    local react_id = frame.args[1]
local a, b = frame.args[1], frame.args[2]
    local property = frame.args[2]
if not (a and b) or not p.react[a] then return "" end
   
local v = p.react[a][b]
    if p.react[react_id] and p.react[react_id][property] then
if v == nil then return "" end
        return mw.text.nowiki(tostring(p.react[react_id][property]))
return mw.text.nowiki(tostring(v))
    end
    return ""
end
end


-- Получение цвета химического вещества
function p.getcolor(frame)
function p.getcolor(frame)
    local chem_id = frame.args[1]
local a = frame.args[1]
   
if not a or not p.chem[a] or not p.chem[a].color then return "" end
    if p.chem[chem_id] and p.chem[chem_id].color then
return mw.text.nowiki(p.chem[a].color:sub(1, 7))
        local color = p.chem[chem_id].color
        -- Обрезаем до 7 символов (#RRGGBB)
        return mw.text.nowiki(color:sub(1, 7))
    end
    return "#FFFFFF"
end
end


-- Получение цвета текста на основе яркости фона
function p.gettextcolor(frame)
function p.gettextcolor(frame)
    local chem_id = frame.args[1]
local a = frame.args[1]
   
if not a or not p.chem[a] or not p.chem[a].color then return mw.text.nowiki("#000") end
    if not (p.chem[chem_id] and p.chem[chem_id].color) then
local basecol = p.chem[a].color
        return "#000"
local red = tonumber(basecol:sub(2, 3), 16) or 0
    end
local grn = tonumber(basecol:sub(4, 5), 16) or 0
   
local blu = tonumber(basecol:sub(6, 7), 16) or 0
    local basecol = p.chem[chem_id].color
local luminance = math.sqrt(0.241*red*red + 0.691*grn*grn + 0.068*blu*blu)
    local red = tonumber(basecol:sub(2, 3), 16) or 0
if luminance > 100 then
    local grn = tonumber(basecol:sub(4, 5), 16) or 0
return mw.text.nowiki("#000")
    local blu = tonumber(basecol:sub(6, 7), 16) or 0
else
   
return mw.text.nowiki("#FFF")
    -- Вычисляем яркость
end
    local luminance = math.sqrt(0.241*red*red + 0.691*grn*grn + 0.068*blu*blu)
   
    if luminance > 100 then
        return mw.text.nowiki("#000")
    else
        return mw.text.nowiki("#FFF")
    end
end
end


-- Проверка наличия рецепта у химического вещества
function p.hasrecipe(frame)
function p.hasrecipe(frame)
    local chem_id = frame.args[1]
local chem = frame.args[1]
   
if not chem or not p.chem[chem] then return "" end
    if p.chem[chem_id] and p.chem[chem_id].recipes then
return (p.chem[chem].recipes and p.chem[chem].recipes[1]) and "true" or ""
        return #p.chem[chem_id].recipes > 0
    end
    return false
end
end


-- Построение блоков для химических веществ
function p.buildboxes(frame)
function p.buildboxes(frame)
    local group = frame.args[1]
local out = ""
    local out = ""
local group = frame.args[1]
   
for k, v in pairs(p.chem) do
    for k, v in pairs(p.chem) do
if type(v) == "table" then
        if group == nil or (v.group and v.group == group) then
if (group == nil) or (v.group == group) then
            out = out .. frame:expandTemplate{  
out = out .. frame:expandTemplate{ title = "Chembox", args = { prototype = k }}
                title = "Chembox",  
end
                args = { prototype = k }
end
            }
end
        end
return out
    end
   
    return out
end
end


-- Построение блоков реакций
function p.buildreactboxes(frame)
function p.buildreactboxes(frame)
    local out = ""
local out = ""
   
for k, v in pairs(p.react) do
    for k, v in pairs(p.react) do
if type(v) == "table" and v.effects and tablelength(v.effects) ~= 0 then
        if v.effects and p.tablelength(v.effects) > 0 then
out = out .. frame:expandTemplate{ title = "Reactionbox", args = { reaction = k }}
            out = out .. frame:expandTemplate{  
end
                title = "Reactionbox",  
end
                args = { reaction = k }
return out
            }
        end
    end
   
    return out
end
end


-- Построение рецептов для химического вещества
function p.buildrecipes(frame)
function p.buildrecipes(frame)
    local chem_id = frame.args[1]
local chem = frame.args[1]
    local out = ""
if not chem or not p.chem[chem] then return "" end
   
local out = ""
    if p.chem[chem_id] and p.chem[chem_id].recipes then
for _, recipe in pairs(p.chem[chem].recipes or {}) do
        for _, recipe_id in pairs(p.chem[chem_id].recipes) do
out = out .. p.buildreaction(frame, recipe)
            out = out .. p.buildreaction(frame, recipe_id)
end
        end
return out
    end
   
    return out
end
end


-- Построение конкретной реакции
-- Версия для консоли отладки без frame
function p.buildreactionext(frame)
function p.buildrecipes_debug(chem)
    local react_id = frame.args[1]
if not chem or not p.chem[chem] then return "Химикат не найден" end
    return p.buildreaction(frame, react_id)
local out = "=== Рецепты для " .. chem .. " ===\n"
for i, recipe in ipairs(p.chem[chem].recipes or {}) do
out = out .. "Рецепт " .. i .. ": " .. recipe .. "\n"
if p.react[recipe] then
local data = p.react[recipe]
out = out .. "  Реактанты:\n"
for k, v in pairs(data.reactants or {}) do
out = out .. "    - " .. k .. ": " .. (v.amount or "?") .. "\n"
end
out = out .. "  Продукты:\n"
for k, v in pairs(data.products or {}) do
out = out .. "    - " .. k .. ": " .. tostring(v) .. "\n"
end
end
out = out .. "\n"
end
return out
end
end


-- Основная функция построения реакции
function p.buildreactionext(frame)
function p.buildreaction(frame, react_id)
local react = frame.args[1]
    if not p.react[react_id] then
return p.buildreaction(frame, react)
        return ""
    end
   
    local data = p.react[react_id]
    local args = {}
   
    -- Обрабатываем реагенты
    local i = 0
    if data.reactants then
        for reagent_id, reagent_data in pairs(data.reactants) do
            i = i + 1
            local dest = "Chemistry"
           
            if p.chem[reagent_id] and p.chem[reagent_id].group and p.groupDirection[p.chem[reagent_id].group] then
                dest = p.groupDirection[p.chem[reagent_id].group]
            end
           
            args["component-" .. i] = frame:expandTemplate{
                title = "Chem Recipe Component",
                args = {
                    reagent = reagent_id,
                    amount = reagent_data.amount or reagent_data,
                    dest = dest
                }
            }
        end
    end
   
    -- Обрабатываем продукты
    i = 0
    if data.products then
        for product_id, amount in pairs(data.products) do
            i = i + 1
            local dest = "Chemistry"
           
            if p.chem[product_id] and p.chem[product_id].group and p.groupDirection[p.chem[product_id].group] then
                dest = p.groupDirection[p.chem[product_id].group]
            end
           
            args["result-" .. i] = frame:expandTemplate{
                title = "Chem Recipe Component",
                args = {
                    reagent = product_id,
                    amount = amount,
                    dest = dest
                }
            }
        end
    end
   
    -- Обрабатываем эффекты
    if data.effects then
        args.effects = p.geneffectlist(data.effects, frame, 1)
    end
   
    return frame:expandTemplate{ title = "Chem Box Recipe", args = args }
end
end


-- Проверка на утоление жажды
function p.buildreaction(frame, react)
function p.checksatiatesthirst(frame)
if not react or not p.react[react] then return "" end
    local chem_id = frame.args[1]
   
-- Проверка для консоли отладки
    if not (p.chem[chem_id] and p.chem[chem_id].metabolisms) then
if not frame or not frame.expandTemplate then
        return ""
return "Рецепт: " .. react .. " (для полного отображения используйте в MediaWiki)"
    end
end
   
    for _, metabolism in pairs(p.chem[chem_id].metabolisms) do
local data = p.react[react]
        if metabolism.effects then
local args = {}
            for _, effect in pairs(metabolism.effects) do
                if effect.id == "SatiateThirst" then
                    return "1"
                end
            end
        end
    end
   
    return ""
end


-- Проверка на утоление голода
-- Реактанты
function p.checksatiateshunger(frame)
local i = 0
    local chem_id = frame.args[1]
for k, v in pairs(data.reactants or {}) do
   
i = i + 1
    if not (p.chem[chem_id] and p.chem[chem_id].metabolisms) then
local dest = p.groupDirection[(p.chem[k] or {}).group] or "Chemistry"
        return ""
args["component-" .. i] = frame:expandTemplate{
    end
title = "Chem Recipe Component",
   
args = { reagent = k, amount = v.amount, dest = dest }
    for _, metabolism in pairs(p.chem[chem_id].metabolisms) do
}
        if metabolism.effects then
end
            for _, effect in pairs(metabolism.effects) do
                if effect.id == "SatiateHunger" then
                    return "1"
                end
            end
        end
    end
   
    return ""
end


-- Проверка наличия эффектов (кроме голода/жажды)
-- Продукты
function p.haseffects(frame)
i = 0
    local chem_id = frame.args[1]
for k, v in pairs(data.products or {}) do
   
i = i + 1
    if not (p.chem[chem_id] and p.chem[chem_id].metabolisms) then
local dest = p.groupDirection[(p.chem[k] or {}).group] or "Chemistry"
        return ""
args["result-" .. i] = frame:expandTemplate{
    end
title = "Chem Recipe Component",
   
args = { reagent = k, amount = v, dest = dest }
    for _, metabolism in pairs(p.chem[chem_id].metabolisms) do
}
        if metabolism.effects then
end
            for _, effect in pairs(metabolism.effects) do
                if effect.id ~= "SatiateHunger" and effect.id ~= "SatiateThirst" then
                    return "1"
                end
            end
        end
    end
   
    return ""
end


-- Генерация эффектов
-- Эффекты реакции (не метаболизм)
function p.geneffects(frame, chem_id)
if data.effects ~= nil then
    if chem_id == nil then
args.effects = p.geneffectlist(data.effects, frame, 1)
        chem_id = frame.args[1]
end
    end
   
    if not (p.chem[chem_id] and p.chem[chem_id].metabolisms) then
        return ""
    end
   
    local out = ""
    for metabolism_type, metabolism_data in pairs(p.chem[chem_id].metabolisms) do
        local rate = metabolism_data.rate or 0.5
        out = out .. "<b>" .. metabolism_type .. "</b> (" .. rate .. " единиц в секунду)\n"
       
        if metabolism_data.effects then
            out = out .. p.geneffectlist(metabolism_data.effects, frame, rate)
        end
    end
   
    return out
end


-- Генерация списка эффектов
return frame:expandTemplate{ title = "Chem Box Recipe", args = args }
function p.geneffectlist(effects, frame, rate)
    local out = ""
   
    for _, effect in pairs(effects) do
        if effect.id == "HealthChange" then
            out = out .. ":" .. p.genhealthchange(effect, rate, frame) .. "\n"
        elseif effect.id == "AdjustReagent" then
            out = out .. ":" .. p.genadjustreagent(effect, rate, frame) .. "\n"
        elseif effect.id == "FlammableReaction" then
            out = out .. ":" .. p.genflammablereaction(effect, frame) .. "\n"
        elseif effect.id == "AdjustTemperature" then
            out = out .. ":" .. p.genadjusttemperature(effect, frame) .. "\n"
        elseif effect.id == "GenericStatusEffect" then
            out = out .. ":" .. p.gengenericstatuseffect(effect, frame) .. "\n"
        elseif effect.id == "ExplosionReactionEffect" then
            out = out .. ":" .. p.genexplosionreactioneffect(effect, frame) .. "\n"
        elseif effect.id == "FoamAreaReactionEffect" then
            out = out .. ":" .. p.genfoamareareactioneffect(effect, frame) .. "\n"
        elseif effect.id == "SmokeAreaReactionEffect" then
            out = out .. ":" .. p.gensmokeareareactioneffect(effect, frame) .. "\n"
        elseif effect.id == "ModifyBleedAmount" then
            out = out .. ":" .. p.genmodifybleedamount(effect, frame) .. "\n"
        end
    end
   
    return out
end
end


-- Генераторы для различных типов эффектов
local function scan_metab(chem)
function p.gensmokeareareactioneffect(effect, frame)
local met = (p.chem[chem] or {}).metabolisms
    local conds = ""
if not met then return nil end
    if effect.conditions then
return met
        conds = p.genconds(effect.conditions, frame)
    end
   
    return frame:expandTemplate{
        title = "SmokeAreaReactionEffect",
        args = {
            when = conds,
            prob = effect.probability
        }
    }
end
end


function p.genfoamareareactioneffect(effect, frame)
function p.checksatiatesthirst(frame)
    local conds = ""
local chem = frame.args[1]
    if effect.conditions then
local met = scan_metab(chem)
        conds = p.genconds(effect.conditions, frame)
if not met then return "" end
    end
for _, v in pairs(met) do
   
for _, w in pairs(v.effects or {}) do
    return frame:expandTemplate{  
-- Исправляем проверку для JSON структуры
        title = "FoamAreaReactionEffect",
local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
        args = {
if effectName == "SatiateThirst" then return "1" end
            when = conds,
end
            prob = effect.probability
end
        }
return ""
    }
end
end


function p.genexplosionreactioneffect(effect, frame)
function p.checksatiateshunger(frame)
    local conds = ""
local chem = frame.args[1]
    if effect.conditions then
local met = scan_metab(chem)
        conds = p.genconds(effect.conditions, frame)
if not met then return "" end
    end
for _, v in pairs(met) do
   
for _, w in pairs(v.effects or {}) do
    return frame:expandTemplate{  
-- Исправляем проверку для JSON структуры
        title = "ExplosionReactionEffect",
local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
        args = {
if effectName == "SatiateHunger" then return "1" end
            when = conds,
end
            prob = effect.probability
end
        }
return ""
    }
end
end


function p.gengenericstatuseffect(effect, frame)
function p.haseffects(frame)
    local conds = ""
local chem = frame.args[1]
    if effect.conditions then
local met = scan_metab(chem)
        conds = p.genconds(effect.conditions, frame)
if not met then return "" end
    end
for _, v in pairs(met) do
   
for _, w in pairs(v.effects or {}) do
    return frame:expandTemplate{
-- Исправляем проверку для JSON структуры
        title = "GenericStatusEffect",  
local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
        args = {  
if effectName ~= "SatiateHunger" and effectName ~= "SatiateThirst" then
            key = effect.Key,
return "1"
            type = effect.Type,
end
            time = effect.Time,
end
            refresh = effect.Refresh,
end
            when = conds,
return ""
            prob = effect.probability
        }
    }
end
end


function p.genadjusttemperature(effect, frame)
function p.geneffects(frame, chem)
    local conds = ""
if chem == nil then chem = frame.args[1] end
    if effect.conditions then  
local met = scan_metab(chem)
        conds = p.genconds(effect.conditions, frame)
if not met then return "" end
    end
local out = ""
   
for k, v in pairs(met) do
    return frame:expandTemplate{
-- Исправляем вывод rate - теперь используем правильное поле
        title = "AdjustTemperature",
local rate = v.rate or 1.0
        args = {
            amount = effect.Amount,  
-- Получаем локализованное название группы метаболизма
            when = conds,
local groupName = k
            prob = effect.probability
if p.status and p.status[k] and p.status[k].name then
        }
groupName = p.status[k].name
    }
end
out = out .. "<b>" .. groupName .. "</b>\n"
-- Генерируем эффекты для этой группы
local effectsText = p.geneffectlist(v.effects or {}, frame, rate)
out = out .. effectsText
out = out .. "\n"
end
return out
end
end


function p.genflammablereaction(effect, frame)
function p.geneffectlist(effects, frame, rate)
    local conds = ""
local out = ""
    if effect.conditions then  
for _, w in pairs(effects or {}) do
        conds = p.genconds(effect.conditions, frame)
-- Исправляем получение ID эффекта для JSON структуры
    end
local effectId = (type(w.type) == "table" and w.type.name) or w.type or w.id or ""
   
    return frame:expandTemplate{
-- Обрабатываем условия для всех эффектов
        title = "FlammableReaction",  
local conditionsText = ""
        args = {
if w.conditions then
            multiplier = effect.Multiplier,  
-- Проверяем есть ли хотя бы одно условие
            when = conds,
local hasConditions = false
            prob = effect.probability
for _ in pairs(w.conditions) do
        }
hasConditions = true
    }
break
end
if hasConditions then
conditionsText = " если " .. p.genconds(w.conditions, frame or {})
end
end
-- Применяем factor ко всем эффектам
local factor = w.factor or 1
local effectText = ""
if effectId == "SatiateThirst" then
local text = (type(w.type) == "table" and w.type.text) or "Утоляет жажду"
if factor ~= 1 then
effectText = text .. " на " .. tostring(factor) .. "x от обычного"
else
effectText = text
end
elseif effectId == "SatiateHunger" then
local text = (type(w.type) == "table" and w.type.text) or "Утоляет голод"
if factor ~= 1 then
effectText = text .. " на " .. tostring(factor) .. "x от обычного"
else
effectText = text
end
elseif effectId == "HealthChange" then
effectText = p.genhealthchange(w, rate, frame or {})
elseif effectId == "AdjustReagent" then
effectText = p.genadjustreagent(w, rate, frame or {})
-- Добавьте другие типы эффектов по необходимости
end
if effectText ~= "" then
out = out .. effectText .. conditionsText .. "\n"
end
end
return out
end
end


function p.genadjustreagent(effect, rate, frame)
    local conds = ""
    if effect.conditions then
        conds = p.genconds(effect.conditions, frame)
    end
   
    return frame:expandTemplate{
        title = "AdjustReagent",
        args = {
            amount = effect.Amount,
            reagent = effect.Reagent,
            when = conds,
            prob = effect.probability
        }
    }
end


function p.genmodifybleedamount(effect, frame)
    local conds = ""
    if effect.conditions then
        conds = p.genconds(effect.conditions, frame)
    end
   
    return frame:expandTemplate{
        title = "ModifyBleedAmount",
        args = {
            amount = effect.Amount,
            when = conds,
            prob = effect.probability
        }
    }
end


function p.genhealthchange(effect, rate, frame)
    local healst = {}
    local dealst = {}
    local r = 1.0 / rate
   
    if effect.damage and effect.damage.types then
        for damage_type, amount in pairs(effect.damage.types) do
            if amount < 0 then
                healst[damage_type] = amount * r
            else
                dealst[damage_type] = amount * r
            end
        end
    end
   
    if effect.damage and effect.damage.groups then
        for damage_group, amount in pairs(effect.damage.groups) do
            if amount < 0 then
                healst[damage_group] = amount * r
            else
                dealst[damage_group] = amount * r
            end
        end
    end
   
    local heals = p.hchangelist(healst, frame)
    local deals = p.hchangelist(dealst, frame)
    local conds = ""
   
    if effect.conditions then
        conds = p.genconds(effect.conditions, frame)
    end
   
    return frame:expandTemplate{
        title = "HealthChange",
        args = {
            heals = heals,
            deals = deals,
            when = conds,
            prob = effect.probability
        }
    }
end


function p.hchangelist(changes, frame)
    local out = ""
    local len = p.tablelength(changes)
    local i = 0
   
    for damage_type, amount in pairs(changes) do
        i = i + 1
        if len == i and i ~= 1 then
            out = out .. ", and "
        elseif i ~= 1 then
            out = out .. ", "
        end
        out = out .. p.hchange(damage_type, amount, frame)
    end
   
    return out
end


function p.hchange(damage_type, amount, frame)
function p.gensmokeareareactioneffect(r, frame)
    return frame:expandTemplate{  
local conds = nil
        title = "HealthModifier",  
if r.conditions ~= nil then
        args = {  
conds = p.genconds(r.conditions, frame)
            adj = amount,  
end
            kind = damage_type
return frame:expandTemplate{ title = "SmokeAreaReactionEffect", args = { when = conds, prob = r.probability }}
        }
    }
end
end


function p.genconds(conditions, frame)
function p.genfoamareareactioneffect(r, frame)
    local out = ""
local conds = nil
    local len = p.tablelength(conditions)
if r.conditions ~= nil then
    local i = 0
conds = p.genconds(r.conditions, frame)
   
end
    for _, condition in pairs(conditions) do
return frame:expandTemplate{ title = "FoamAreaReactionEffect", args = { when = conds, prob = r.probability }}
        i = i + 1
        if len == i and i ~= 1 then
            out = out .. ", and "
        elseif i ~= 1 then
            out = out .. ", "
        end
        out = out .. p.gencond(condition, frame)
    end
   
    return out
end
end


function p.gencond(condition, frame)
function p.genexplosionreactioneffect(r, frame)
    if condition.id == "TotalDamage" then
local conds = nil
        return frame:expandTemplate{
if r.conditions ~= nil then  
            title = "TotalDamage",
conds = p.genconds(r.conditions, frame)
            args = {
end
                min = condition.Min,
return frame:expandTemplate{ title = "ExplosionReactionEffect", args = { when = conds, prob = r.probability }}
                max = condition.Max
            }
        }
    elseif condition.id == "ReagentThreshold" then
        return frame:expandTemplate{
            title = "ReagentThreshold",
            args = {
                min = condition.Min,
                max = condition.Max,  
                reagent = condition.Reagent
            }
        }
    elseif condition.id == "OrganType" then
        return frame:expandTemplate{
            title = "OrganType",
            args = {
                shouldhave = condition.ShouldHave,
                type = condition.Type
            }
        }
    elseif condition.id == "Temperature" then
        return frame:expandTemplate{  
            title = "Temperature",  
            args = {  
                min = condition.Min,  
                max = condition.Max
            }
        }
    end
   
    return ""
end
end


-- Вспомогательные функции
function p.gengenericstatuseffect(r, frame)
function p.tablelength(table)
local conds = nil
    local count = 0
if r.conditions ~= nil then
    for _ in pairs(table) do
conds = p.genconds(r.conditions, frame)
        count = count + 1
end
    end
return frame:expandTemplate{
    return count
title = "GenericStatusEffect",
args = { key = r.Key or r.key, type = r.Type, time = r.Time or r.time, refresh = r.Refresh, when = conds, prob = r.probability }
}
end
end


function p.has_value(tab, val)
function p.genadjusttemperature(r, frame)
    for _, value in ipairs(tab) do
local conds = nil
        if value[1] == val then
if r.conditions ~= nil then  
            return true
conds = p.genconds(r.conditions, frame)
        end
end
    end
return frame:expandTemplate{ title = "AdjustTemperature", args = { amount = r.Amount or r.amount, when = conds, prob = r.probability }}
    return false
end
 
function p.strsplit(inputstr, separator)
    if separator == nil then
        separator = ","
    end
   
    local t = {}
    for str in string.gmatch(inputstr, "([^"..separator.."]+)") do
        table.insert(t, str)
    end
   
    return t
end
 
-- Функции для работы со статусами химических веществ
function p.getmetabolizertype(frame)
    local type_id = frame.args[1]
   
    if p.status[type_id] and p.status[type_id].type == "metabolizerType" then
        return p.status[type_id].name or type_id
    end
   
    return ""
end
 
function p.getmetabolismgroup(frame)
    local group_id = frame.args[1]
   
    if p.status[group_id] and p.status[group_id].type == "metabolismGroup" then
        return p.status[group_id].name or group_id
    end
   
    return ""
end
 
function p.getmixingcategory(frame)
    local category_id = frame.args[1]
   
    if p.status[category_id] and p.status[category_id].type == "mixingCategory" then
        return p.status[category_id].verbText or category_id
    end
   
    return ""
end
 
function p.getreactivegroup(frame)
    local group_id = frame.args[1]
   
    if p.status[group_id] and p.status[group_id].type == "reactiveGroup" then
        return group_id
    end
   
    return ""
end
 
-- Дополнительные функции для ваших шаблонов
 
-- Проверка наличия особых эффектов
function p.hasspecialeffects(frame)
    local chem_id = frame.args[1]
   
    if not (p.chem[chem_id] and p.chem[chem_id].tileReactions) then
        return ""
    end
   
    -- Проверяем наличие особых эффектов в tileReactions
    for _, reaction in pairs(p.chem[chem_id].tileReactions) do
        if reaction.effects and #reaction.effects > 0 then
            return "true"
        end
    end
   
    return ""
end
end


-- Генерация особых эффектов
function p.genflammablereaction(r, frame)
function p.genspecialeffects(frame)
local conds = nil
    local chem_id = frame.args[1]
if r.conditions ~= nil then
   
conds = p.genconds(r.conditions, frame)
    if not (p.chem[chem_id] and p.chem[chem_id].tileReactions) then
end
        return ""
return frame:expandTemplate{ title = "FlammableReaction", args = { multiplier = r.Multiplier, when = conds, prob = r.probability }}
    end
   
    local out = ""
    for _, reaction in pairs(p.chem[chem_id].tileReactions) do
        if reaction.effects then
            out = out .. p.geneffectlist(reaction.effects, frame, 1)
        end
    end
   
    return out
end
end


-- Проверка наличия эффектов плитки
function p.genadjustreagent(r, rate, frame)
function p.hastileeffects(frame)
local factor = r.factor or 1
    local chem_id = frame.args[1]
local amount = (r.amount or r.Amount or 0) * factor
   
local reagent = r.reagent or r.Reagent or "неизвестный реагент"
    if not (p.chem[chem_id] and p.chem[chem_id].plantMetabolism) then
        return ""
if amount > 0 then
    end
return "<span style='color: #4dabf7'>Добавляет " .. tostring(amount) .. " ед. " .. reagent .. "</span>"
   
else
    -- Проверяем наличие эффектов в plantMetabolism
return "<span style='color: #ffa8a8'>Удаляет " .. tostring(-amount) .. " ед. " .. reagent .. "</span>"
    for _, metabolism in pairs(p.chem[chem_id].plantMetabolism) do
end
        if metabolism.effects and #metabolism.effects > 0 then
            return "true"
        end
    end
   
    return ""
end
end


-- Генерация эффектов плитки
function p.genmodifybleedamount(r, frame)
function p.gentileeffects(frame)
local conds = nil
    local chem_id = frame.args[1]
if r.conditions ~= nil then
   
conds = p.genconds(r.conditions, frame)
    if not (p.chem[chem_id] and p.chem[chem_id].plantMetabolism) then
end
        return ""
return frame:expandTemplate{ title = "ModifyBleedAmount", args = { amount = r.Amount or r.amount, when = conds, prob = r.probability }}
    end
   
    local out = ""
    for metabolism_type, metabolism_data in pairs(p.chem[chem_id].plantMetabolism) do
        local rate = metabolism_data.rate or 0.5
        out = out .. "<b>" .. metabolism_type .. "</b> (" .. rate .. " единиц в секунду)\n"
       
        if metabolism_data.effects then
            out = out .. p.geneffectlist(metabolism_data.effects, frame, rate)
        end
    end
   
    return out
end
end


-- Улучшенная функция readscalar с поддержкой fallback
function p.genhealthchange(h, rate, frame)
function p.readscalar_with_fallback(frame)
local effects = {}
    local chem_id = frame.args[1]
local factor = h.factor or 1
    local property = frame.args[2]
    local fallback = frame.args.fallback or frame.args[3] or ""
if h.damage and h.damage.types then
   
for damageType, amount in pairs(h.damage.types) do
    if p.chem[chem_id] and p.chem[chem_id][property] then
local finalAmount = amount * factor
        return mw.text.nowiki(tostring(p.chem[chem_id][property]))
if finalAmount > 0 then
    end
table.insert(effects, "<span style='color: #ff6b6b'>Наносит " .. tostring(finalAmount) .. " ед. " .. damageType .. "</span>")
    return fallback
else
table.insert(effects, "<span style='color: #51cf66'>Лечит " .. tostring(-finalAmount) .. " ед. " .. damageType .. "</span>")
end
end
end
if h.damage and h.damage.groups then
for damageGroup, amount in pairs(h.damage.groups) do
local finalAmount = amount * factor
if finalAmount > 0 then
table.insert(effects, "<span style='color: #ff6b6b'>Наносит " .. tostring(finalAmount) .. " ед. " .. damageGroup .. "</span>")
else
table.insert(effects, "<span style='color: #51cf66'>Лечит " .. tostring(-finalAmount) .. " ед. " .. damageGroup .. "</span>")
end
end
end
return table.concat(effects, "<br/>")
end
end


-- Функция для получения описания химического вещества
function p.genconds(conds, frame)
function p.getdesc(frame)
local out = ""
    local chem_id = frame.args[1]
local len = tablelength(conds or {})
   
local i = 0
    if p.chem[chem_id] and p.chem[chem_id].desc then
for _, c in pairs(conds or {}) do
        return p.chem[chem_id].desc
i = i + 1
    end
if len == i and i ~= 1 then
    return ""
out = out .. ", and "
elseif i ~= 1 then
out = out .. ", "
end
out = out .. p.gencond(c, frame)
end
return out
end
end


-- Функция для получения физического описания
function p.gencond(c, frame)
function p.getphysicaldesc(frame)
if not c or not c.type then return "" end
    local chem_id = frame.args[1]
if c.type == "TotalDamage" then
   
-- Если нет frame, формируем текст напрямую
    if p.chem[chem_id] and p.chem[chem_id].physicalDesc then
if not frame or not frame.expandTemplate then
        return p.chem[chem_id].physicalDesc
local min = c.Min or c.min or "?"
    end
local max = c.Max or c.max or "?"
    return "бесцветная жидкость"
return "общий урон между " .. tostring(min) .. " и " .. tostring(max)
end
return frame:expandTemplate{ title = "TotalDamage", args = { min = c.Min or c.min, max = c.Max or c.max } }
elseif c.type == "ReagentThreshold" then
-- Если нет frame, формируем текст напрямую
if not frame or not frame.expandTemplate then
local min = c.Min or c.min or 0
local max = c.Max or c.max or "∞"
local reagent = c.Reagent or c.reagent or "неизвестный реагент"
return reagent .. " между " .. tostring(min) .. " и " .. tostring(max) .. " единиц"
end
return frame:expandTemplate{ title = "ReagentThreshold", args = { min = c.Min or c.min, max = c.Max or c.max, reagent = c.Reagent or c.reagent } }
elseif c.type == "Temperature" then
-- Если нет frame, формируем текст напрямую
if not frame or not frame.expandTemplate then
local min = c.Min or c.min or "?"
local max = c.Max or c.max or "?"
return "температура между " .. tostring(min) .. " и " .. tostring(max)
end
return frame:expandTemplate{ title = "Temperature", args = { min = c.Min or c.min, max = c.Max or c.max } }
else
-- Новая логика: если type не является стандартным условием, то это тип органа
local organTypeName = c.type
local shouldHave = c.shouldHave
if shouldHave == nil then shouldHave = true end
-- Получаем локализованное название типа органа из status данных
if p.status and p.status[organTypeName] and p.status[organTypeName].name then
organTypeName = p.status[organTypeName].name
end
-- Формируем текст условия напрямую
if shouldHave then
return "метаболизирующий орган это " .. organTypeName .. " орган"
else
return "метаболизирующий орган не " .. organTypeName .. " орган"
end
end
return ""
end
end


-- Функция для построения кнопок химических веществ
-- Отладочная функция для проверки рецептов
function p.buildchembuttons(frame)
function p.debugrecipes(frame)
    local group = frame.args[1]
local chem = frame.args[1]
    local out = ""
if not chem then return "Не указан химикат" end
   
    for k, v in pairs(p.chem) do
local out = "=== Отладка рецептов для " .. chem .. " ===\n"
        if group == nil or (v.group and v.group == group) then
            out = out .. frame:expandTemplate{
-- Проверяем существует ли химикат
                title = "Chemical button",
if not p.chem[chem] then
                args = { k, "1" }
out = out .. "ОШИБКА: Химикат не найден в базе данных\n"
            }
return out
        end
end
    end
   
-- Проверяем есть ли рецепты
    return out
local recipes = p.chem[chem].recipes
if not recipes then
out = out .. "Рецепты не найдены (recipes = nil)\n"
-- Попробуем найти рецепты вручную
out = out .. "Поиск рецептов в реакциях:\n"
for reactId, reactData in pairs(p.react) do
if reactData.products and reactData.products[chem] then
out = out .. "- Найдена реакция: " .. reactId .. " (производит " .. tostring(reactData.products[chem]) .. ")\n"
end
end
else
-- Подсчитываем рецепты правильно
local recipeCount = 0
for _ in pairs(recipes) do
recipeCount = recipeCount + 1
end
out = out .. "Найдено рецептов: " .. recipeCount .. "\n"
for i, recipe in ipairs(recipes) do
out = out .. "- Рецепт " .. i .. ": " .. recipe .. "\n"
if p.react[recipe] then
out = out .. "  Реакция существует: да\n"
if p.react[recipe].products and p.react[recipe].products[chem] then
out = out .. "  Производит " .. chem .. ": " .. tostring(p.react[recipe].products[chem]) .. "\n"
else
out = out .. " ОШИБКА: Не производит " .. chem .. "\n"
end
else
out = out .. " ОШИБКА: Реакция не существует\n"
end
end
end
return out
end
end


return p
return p

Текущая версия от 00:14, 7 сентября 2025

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

local prototypes = mw.loadData("Module:Chemistry Lookup/data")

local p = {}
p.chem = prototypes.chem or {}
p.react = prototypes.react or {}
p.status = prototypes.status or {}
p.groupDirection = prototypes.groupDirection or {}

-- ===== Хелперы =====
local function tablelength(T)
	local count = 0
	for _ in pairs(T or {}) do count = count + 1 end
	return count
end

local function hchangelist(l, frame)
	local out = ""
	local len = tablelength(l)
	local i = 0
	for k, v in pairs(l) do
		i = i + 1
		if len == i and i ~= 1 then
			out = out .. ", and "
		elseif i ~= 1 then
			out = out .. ", "
		end
		out = out .. frame:expandTemplate{ title = "HealthModifier", args = { adj = v, kind = k } }
	end
	return out
end

function p.readscalar(frame)
	local a, b = frame.args[1], frame.args[2]
	if not (a and b) or not p.chem[a] then return "" end
	local v = p.chem[a][b]
	if v == nil then return "" end
	return mw.text.nowiki(tostring(v))
end

function p.readscalarreact(frame)
	local a, b = frame.args[1], frame.args[2]
	if not (a and b) or not p.react[a] then return "" end
	local v = p.react[a][b]
	if v == nil then return "" end
	return mw.text.nowiki(tostring(v))
end

function p.getcolor(frame)
	local a = frame.args[1]
	if not a or not p.chem[a] or not p.chem[a].color then return "" end
	return mw.text.nowiki(p.chem[a].color:sub(1, 7))
end

function p.gettextcolor(frame)
	local a = frame.args[1]
	if not a or not p.chem[a] or not p.chem[a].color then return mw.text.nowiki("#000") end
	local basecol = p.chem[a].color
	local red = tonumber(basecol:sub(2, 3), 16) or 0
	local grn = tonumber(basecol:sub(4, 5), 16) or 0
	local blu = tonumber(basecol:sub(6, 7), 16) or 0
	local luminance = math.sqrt(0.241*red*red + 0.691*grn*grn + 0.068*blu*blu)
	if luminance > 100 then
		return mw.text.nowiki("#000")
	else
		return mw.text.nowiki("#FFF")
	end
end

function p.hasrecipe(frame)
	local chem = frame.args[1]
	if not chem or not p.chem[chem] then return "" end
	return (p.chem[chem].recipes and p.chem[chem].recipes[1]) and "true" or ""
end

function p.buildboxes(frame)
	local out = ""
	local group = frame.args[1]
	for k, v in pairs(p.chem) do
		if type(v) == "table" then
			if (group == nil) or (v.group == group) then
				out = out .. frame:expandTemplate{ title = "Chembox", args = { prototype = k }}
			end
		end
	end
	return out
end

function p.buildreactboxes(frame)
	local out = ""
	for k, v in pairs(p.react) do
		if type(v) == "table" and v.effects and tablelength(v.effects) ~= 0 then
			out = out .. frame:expandTemplate{ title = "Reactionbox", args = { reaction = k }}
		end
	end
	return out
end

function p.buildrecipes(frame)
	local chem = frame.args[1]
	if not chem or not p.chem[chem] then return "" end
	local out = ""
	for _, recipe in pairs(p.chem[chem].recipes or {}) do
		out = out .. p.buildreaction(frame, recipe)
	end
	return out
end

-- Версия для консоли отладки без frame
function p.buildrecipes_debug(chem)
	if not chem or not p.chem[chem] then return "Химикат не найден" end
	local out = "=== Рецепты для " .. chem .. " ===\n"
	for i, recipe in ipairs(p.chem[chem].recipes or {}) do
		out = out .. "Рецепт " .. i .. ": " .. recipe .. "\n"
		if p.react[recipe] then
			local data = p.react[recipe]
			out = out .. "  Реактанты:\n"
			for k, v in pairs(data.reactants or {}) do
				out = out .. "    - " .. k .. ": " .. (v.amount or "?") .. "\n"
			end
			out = out .. "  Продукты:\n"
			for k, v in pairs(data.products or {}) do
				out = out .. "    - " .. k .. ": " .. tostring(v) .. "\n"
			end
		end
		out = out .. "\n"
	end
	return out
end

function p.buildreactionext(frame)
	local react = frame.args[1]
	return p.buildreaction(frame, react)
end

function p.buildreaction(frame, react)
	if not react or not p.react[react] then return "" end
	
	-- Проверка для консоли отладки
	if not frame or not frame.expandTemplate then
		return "Рецепт: " .. react .. " (для полного отображения используйте в MediaWiki)"
	end
	
	local data = p.react[react]
	local args = {}

	-- Реактанты
	local i = 0
	for k, v in pairs(data.reactants or {}) do
		i = i + 1
		local dest = p.groupDirection[(p.chem[k] or {}).group] or "Chemistry"
		args["component-" .. i] = frame:expandTemplate{
			title = "Chem Recipe Component",
			args = { reagent = k, amount = v.amount, dest = dest }
		}
	end

	-- Продукты
	i = 0
	for k, v in pairs(data.products or {}) do
		i = i + 1
		local dest = p.groupDirection[(p.chem[k] or {}).group] or "Chemistry"
		args["result-" .. i] = frame:expandTemplate{
			title = "Chem Recipe Component",
			args = { reagent = k, amount = v, dest = dest }
		}
	end

	-- Эффекты реакции (не метаболизм)
	if data.effects ~= nil then
		args.effects = p.geneffectlist(data.effects, frame, 1)
	end

	return frame:expandTemplate{ title = "Chem Box Recipe", args = args }
end

local function scan_metab(chem)
	local met = (p.chem[chem] or {}).metabolisms
	if not met then return nil end
	return met
end

function p.checksatiatesthirst(frame)
	local chem = frame.args[1]
	local met = scan_metab(chem)
	if not met then return "" end
	for _, v in pairs(met) do
		for _, w in pairs(v.effects or {}) do
			-- Исправляем проверку для JSON структуры
			local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
			if effectName == "SatiateThirst" then return "1" end
		end
	end
	return ""
end

function p.checksatiateshunger(frame)
	local chem = frame.args[1]
	local met = scan_metab(chem)
	if not met then return "" end
	for _, v in pairs(met) do
		for _, w in pairs(v.effects or {}) do
			-- Исправляем проверку для JSON структуры
			local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
			if effectName == "SatiateHunger" then return "1" end
		end
	end
	return ""
end

function p.haseffects(frame)
	local chem = frame.args[1]
	local met = scan_metab(chem)
	if not met then return "" end
	for _, v in pairs(met) do
		for _, w in pairs(v.effects or {}) do
			-- Исправляем проверку для JSON структуры
			local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
			if effectName ~= "SatiateHunger" and effectName ~= "SatiateThirst" then
				return "1"
			end
		end
	end
	return ""
end

function p.geneffects(frame, chem)
	if chem == nil then chem = frame.args[1] end
	local met = scan_metab(chem)
	if not met then return "" end
	local out = ""
	for k, v in pairs(met) do
		-- Исправляем вывод rate - теперь используем правильное поле
		local rate = v.rate or 1.0
		
		-- Получаем локализованное название группы метаболизма
		local groupName = k
		if p.status and p.status[k] and p.status[k].name then
			groupName = p.status[k].name
		end
		
		out = out .. "<b>" .. groupName .. "</b>\n"
		
		-- Генерируем эффекты для этой группы
		local effectsText = p.geneffectlist(v.effects or {}, frame, rate)
		out = out .. effectsText
		out = out .. "\n"
	end
	return out
end

function p.geneffectlist(effects, frame, rate)
	local out = ""
	for _, w in pairs(effects or {}) do
		-- Исправляем получение ID эффекта для JSON структуры
		local effectId = (type(w.type) == "table" and w.type.name) or w.type or w.id or ""
		
		-- Обрабатываем условия для всех эффектов
		local conditionsText = ""
		if w.conditions then
			-- Проверяем есть ли хотя бы одно условие
			local hasConditions = false
			for _ in pairs(w.conditions) do
				hasConditions = true
				break
			end
			if hasConditions then
				conditionsText = " если " .. p.genconds(w.conditions, frame or {})
			end
		end
		
		-- Применяем factor ко всем эффектам
		local factor = w.factor or 1
		local effectText = ""
		
		if effectId == "SatiateThirst" then
			local text = (type(w.type) == "table" and w.type.text) or "Утоляет жажду"
			if factor ~= 1 then
				effectText = text .. " на " .. tostring(factor) .. "x от обычного"
			else
				effectText = text
			end
		elseif effectId == "SatiateHunger" then
			local text = (type(w.type) == "table" and w.type.text) or "Утоляет голод"
			if factor ~= 1 then
				effectText = text .. " на " .. tostring(factor) .. "x от обычного"
			else
				effectText = text
			end
		elseif effectId == "HealthChange" then
			effectText = p.genhealthchange(w, rate, frame or {})
		elseif effectId == "AdjustReagent" then
			effectText = p.genadjustreagent(w, rate, frame or {})
		-- Добавьте другие типы эффектов по необходимости
		end
		
		if effectText ~= "" then
			out = out .. effectText .. conditionsText .. "\n"
		end
	end
	return out
end





function p.gensmokeareareactioneffect(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "SmokeAreaReactionEffect", args = { when = conds, prob = r.probability }}
end

function p.genfoamareareactioneffect(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "FoamAreaReactionEffect", args = { when = conds, prob = r.probability }}
end

function p.genexplosionreactioneffect(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "ExplosionReactionEffect", args = { when = conds, prob = r.probability }}
end

function p.gengenericstatuseffect(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{
		title = "GenericStatusEffect",
		args = { key = r.Key or r.key, type = r.Type, time = r.Time or r.time, refresh = r.Refresh, when = conds, prob = r.probability }
	}
end

function p.genadjusttemperature(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "AdjustTemperature", args = { amount = r.Amount or r.amount, when = conds, prob = r.probability }}
end

function p.genflammablereaction(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "FlammableReaction", args = { multiplier = r.Multiplier, when = conds, prob = r.probability }}
end

function p.genadjustreagent(r, rate, frame)
	local factor = r.factor or 1
	local amount = (r.amount or r.Amount or 0) * factor
	local reagent = r.reagent or r.Reagent or "неизвестный реагент"
	
	if amount > 0 then
		return "<span style='color: #4dabf7'>Добавляет " .. tostring(amount) .. " ед. " .. reagent .. "</span>"
	else
		return "<span style='color: #ffa8a8'>Удаляет " .. tostring(-amount) .. " ед. " .. reagent .. "</span>"
	end
end

function p.genmodifybleedamount(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "ModifyBleedAmount", args = { amount = r.Amount or r.amount, when = conds, prob = r.probability }}
end

function p.genhealthchange(h, rate, frame)
	local effects = {}
	local factor = h.factor or 1
	
	if h.damage and h.damage.types then
		for damageType, amount in pairs(h.damage.types) do
			local finalAmount = amount * factor
			if finalAmount > 0 then
				table.insert(effects, "<span style='color: #ff6b6b'>Наносит " .. tostring(finalAmount) .. " ед. " .. damageType .. "</span>")
			else
				table.insert(effects, "<span style='color: #51cf66'>Лечит " .. tostring(-finalAmount) .. " ед. " .. damageType .. "</span>")
			end
		end
	end
	
	if h.damage and h.damage.groups then
		for damageGroup, amount in pairs(h.damage.groups) do
			local finalAmount = amount * factor
			if finalAmount > 0 then
				table.insert(effects, "<span style='color: #ff6b6b'>Наносит " .. tostring(finalAmount) .. " ед. " .. damageGroup .. "</span>")
			else
				table.insert(effects, "<span style='color: #51cf66'>Лечит " .. tostring(-finalAmount) .. " ед. " .. damageGroup .. "</span>")
			end
		end
	end
	
	return table.concat(effects, "<br/>")
end

function p.genconds(conds, frame)
	local out = ""
	local len = tablelength(conds or {})
	local i = 0
	for _, c in pairs(conds or {}) do
		i = i + 1
		if len == i and i ~= 1 then
			out = out .. ", and "
		elseif i ~= 1 then
			out = out .. ", "
		end
		out = out .. p.gencond(c, frame)
	end
	return out
end

function p.gencond(c, frame)
	if not c or not c.type then return "" end
	if c.type == "TotalDamage" then
		-- Если нет frame, формируем текст напрямую
		if not frame or not frame.expandTemplate then
			local min = c.Min or c.min or "?"
			local max = c.Max or c.max or "?"
			return "общий урон между " .. tostring(min) .. " и " .. tostring(max)
		end
		return frame:expandTemplate{ title = "TotalDamage", args = { min = c.Min or c.min, max = c.Max or c.max } }
	elseif c.type == "ReagentThreshold" then
		-- Если нет frame, формируем текст напрямую
		if not frame or not frame.expandTemplate then
			local min = c.Min or c.min or 0
			local max = c.Max or c.max or "∞"
			local reagent = c.Reagent or c.reagent or "неизвестный реагент"
			return reagent .. " между " .. tostring(min) .. " и " .. tostring(max) .. " единиц"
		end
		return frame:expandTemplate{ title = "ReagentThreshold", args = { min = c.Min or c.min, max = c.Max or c.max, reagent = c.Reagent or c.reagent } }
	elseif c.type == "Temperature" then
		-- Если нет frame, формируем текст напрямую
		if not frame or not frame.expandTemplate then
			local min = c.Min or c.min or "?"
			local max = c.Max or c.max or "?"
			return "температура между " .. tostring(min) .. " и " .. tostring(max)
		end
		return frame:expandTemplate{ title = "Temperature", args = { min = c.Min or c.min, max = c.Max or c.max } }
	else
		-- Новая логика: если type не является стандартным условием, то это тип органа
		local organTypeName = c.type
		local shouldHave = c.shouldHave
		if shouldHave == nil then shouldHave = true end
		
		-- Получаем локализованное название типа органа из status данных
		if p.status and p.status[organTypeName] and p.status[organTypeName].name then
			organTypeName = p.status[organTypeName].name
		end
		
		-- Формируем текст условия напрямую
		if shouldHave then
			return "метаболизирующий орган это " .. organTypeName .. " орган"
		else
			return "метаболизирующий орган не " .. organTypeName .. " орган"
		end
	end
	return ""
end

-- Отладочная функция для проверки рецептов
function p.debugrecipes(frame)
	local chem = frame.args[1]
	if not chem then return "Не указан химикат" end
	
	local out = "=== Отладка рецептов для " .. chem .. " ===\n"
	
	-- Проверяем существует ли химикат
	if not p.chem[chem] then
		out = out .. "ОШИБКА: Химикат не найден в базе данных\n"
		return out
	end
	
	-- Проверяем есть ли рецепты
	local recipes = p.chem[chem].recipes
	if not recipes then
		out = out .. "Рецепты не найдены (recipes = nil)\n"
		-- Попробуем найти рецепты вручную
		out = out .. "Поиск рецептов в реакциях:\n"
		for reactId, reactData in pairs(p.react) do
			if reactData.products and reactData.products[chem] then
				out = out .. "- Найдена реакция: " .. reactId .. " (производит " .. tostring(reactData.products[chem]) .. ")\n"
			end
		end
	else
		-- Подсчитываем рецепты правильно
		local recipeCount = 0
		for _ in pairs(recipes) do
			recipeCount = recipeCount + 1
		end
		out = out .. "Найдено рецептов: " .. recipeCount .. "\n"
		
		for i, recipe in ipairs(recipes) do
			out = out .. "- Рецепт " .. i .. ": " .. recipe .. "\n"
			if p.react[recipe] then
				out = out .. "  Реакция существует: да\n"
				if p.react[recipe].products and p.react[recipe].products[chem] then
					out = out .. "  Производит " .. chem .. ": " .. tostring(p.react[recipe].products[chem]) .. "\n"
				else
					out = out .. "  ОШИБКА: Не производит " .. chem .. "\n"
				end
			else
				out = out .. "  ОШИБКА: Реакция не существует\n"
			end
		end
	end
	
	return out
end

return p