----------------------------------------------------------
-- Category_Junk.lua
-- Token-based rules (v3.8)
----------------------------------------------------------

local C = {}
C.parent = "Junk"

-- token tables
local TOKENS = {
    Dung   = { "dung", "droppings", "feces", "faeces" },
    Broken = { "broken" },
    Smoking = { "pipe", "cheroot", "tobacco", "cigarette", "rolling pappers", "rolling papers" },
}

-- Universal token matcher for all categories
local function matchTokens(text, tokens)
    for _, token in ipairs(tokens) do
        if text:find(token, 1, true) then
            return true
        end
    end
    return false
end

local function lower(val)
    if not val then return "" end
    return string.lower(tostring(val))
end

local function isJunk(item)
    local dc = lower(item.getDisplayCategory and item:getDisplayCategory())
    local cat = lower(item.getCategory and item:getCategory())
    local name = lower(item.getDisplayName and item:getDisplayName())

    -- Considerar rotos como basura
    if dc:find("broken") or cat:find("broken") or (name and name:find("broken")) then
        return true
    end

    return dc:find("junk") ~= nil
end

local function getText(item)
    local name = lower(item.getDisplayName and item:getDisplayName())
    local dc   = lower(item.getDisplayCategory and item:getDisplayCategory())
    return (name or "") .. " " .. (dc or "")
end

C.rules = {
    {
        id = "Junk.BaseCheck",
        priority = 50,
        match = function(item, statMap)
            return isJunk(item)
        end,
        category = "Junk",
    },

    {
        id = "Junk.Dung",
        priority = 100,
        match = function(item, statMap)
            if not isJunk(item) then return false end
            return matchTokens(getText(item), TOKENS.Dung)
        end,
        category = "Junk/Dung",
    },

    {
        id = "Junk.Broken",
        priority = 130,
        match = function(item, statMap)
            if not isJunk(item) then return false end
            return matchTokens(getText(item), TOKENS.Broken)
        end,
        category = "Junk/Broken",
    },

    {
        id = "Junk.Smoking",
        priority = 98,
        match = function(item, statMap)
            if not isJunk(item) then return false end
            return matchTokens(getText(item), TOKENS.Smoking)
        end,
        category = "Junk/Smoking",
    },
}

return C
