local CategoryRules = require "InspectSystem/Core/Inspect_CategoryRules"
local InspectPlugins = {}

-- Lista interna de plugins
InspectPlugins._list = InspectPlugins._list or {}

--------------------------------------------------------
-- Registro de plugins
--------------------------------------------------------
-- def: tabla con campos opcionales:
--   id        (string)  identificador único
--   priority  (number)  prioridad (más alto = antes)
--   describe  (function) override opcional
--   post      (function) post-procesador opcional
--
-- Ambas firmas reciben:
--   (item, statMap, parent, child, baseDescription)
--
function InspectPlugins.register(def)
    -- Validación básica
    if type(def) ~= "table" then return end

    -- Normalizar
    def.id = def.id or ("plugin_" .. tostring(#InspectPlugins._list + 1))
    def.priority = def.priority or 0

    table.insert(InspectPlugins._list, def)

    -- Ordenar por prioridad (descendente)
    table.sort(InspectPlugins._list, function(a, b)
        return (a.priority or 0) > (b.priority or 0)
    end)
end

--------------------------------------------------------
-- Fase 1: intentar override de descripción
--------------------------------------------------------
function InspectPlugins.tryOverride(item, statMap, parent, child)
    for _, plugin in ipairs(InspectPlugins._list) do
        if type(plugin.describe) == "function" then
            local ok, result = pcall(plugin.describe, item, statMap, parent, child, nil)
            if ok and type(result) == "string" and result ~= "" then
                return result
            end
        end
    end
    return nil
end

--------------------------------------------------------
-- Fase 2: post-procesar descripción base
--------------------------------------------------------
function InspectPlugins.postProcess(item, statMap, parent, child, baseDescription)
    local desc = baseDescription or ""
    for _, plugin in ipairs(InspectPlugins._list) do
        if type(plugin.post) == "function" then
            local ok, result = pcall(plugin.post, item, statMap, parent, child, desc)
            if ok and type(result) == "string" and result ~= "" then
                desc = result
            end
        end
    end
    return desc
end

--------------------------------------------------------
-- API global para otros mods (Framework Style)
--------------------------------------------------------
ItemInspection = ItemInspection or {}
ItemInspection.Plugins = ItemInspection.Plugins or {}

-- Función pública que otros mods usarán:
function ItemInspection.RegisterPlugin(def)
    InspectPlugins.register(def)
end

-- Registrar regla de categoría personalizada (Extended Categories)
function ItemInspection.AddCategoryRule(def)
    CategoryRules.register(def)
end

-- Exportar módulo interno
return InspectPlugins
