local CategoryRules = {}

-- Internal list of plugin-defined rules
CategoryRules._rules = {}

--------------------------------------------------------
-- Register a new category rule
--------------------------------------------------------
-- def fields:
--   id       (string) unique
--   priority (number) higher = evaluated first
--   child    (string) category name inside Custom/
--   match    (function(item, statMap)) return true/false
--
function CategoryRules.register(def)
    if type(def) ~= "table" then return end

    def.id = def.id or ("rule_" .. tostring(#CategoryRules._rules + 1))
    def.priority = def.priority or 0
    def.child = def.child or "Unknown"

    table.insert(CategoryRules._rules, def)

    table.sort(CategoryRules._rules, function(a, b)
        return (a.priority or 0) > (b.priority or 0)
    end)
end

--------------------------------------------------------
-- Try to match a custom category
--------------------------------------------------------
function CategoryRules.tryMatch(item, statMap)
    for _, rule in ipairs(CategoryRules._rules) do
        if type(rule.match) == "function" then
            local ok, result = pcall(rule.match, item, statMap)
            if ok and result == true then
                return "Custom", rule.child
            end
        end
    end
    return nil, nil
end

return CategoryRules
