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

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

-- token tables
local TOKENS = {
    Card = { "card" },
    Magazine = { "magazine", "schematic" },
    Map = { "map", "cartography", "atlas" },
}

-- 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 getText(item)
    local name = lower(item.getDisplayName and item:getDisplayName())
    local dc   = lower(item.getDisplayCategory and item:getDisplayCategory())
    return (name or "") .. " " .. (dc or "")
end

local function isLiterature(item)
    if instanceof and instanceof(item, "Literature") then
        return true
    end
    local dc = lower(item.getDisplayCategory and item:getDisplayCategory())
    return dc:find("cartography", 1, true) ~= nil or dc:find("map", 1, true) ~= nil
end

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

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

    {
        id = "Literature.SkillBook",
        priority = 100,
        match = function(item, statMap)
            if not isLiterature(item) then return false end
            return item.getSkillTrained and item:getSkillTrained()
        end,
        category = "Literature/SkillBook",
    },

    {
        id = "Literature.Magazine",
        priority = 90,
        match = function(item, statMap)
            if not isLiterature(item) then return false end
            return matchTokens(getText(item), TOKENS.Magazine)
        end,
        category = "Literature/Magazine",
    },

    {
        id = "Literature.Map",
        priority = 90,
        match = function(item, statMap)
            if not isLiterature(item) then return false end
            return matchTokens(getText(item), TOKENS.Map)
        end,
        category = "Literature/Map",
    },
}

return C
