CCCPaste

c58306c449423

local me = peripheral.find("me_bridge")
local trashPeripheral = "minecraft:chest_0"

local check_interval = 20
local running = true

print(textutils.formatTime(os.time())..": Spell management system started. Checking every " .. check_interval .. " seconds.")

local function trim(string)
    return string:gsub("^%s*(.-)%s*$", "%1")
end
local function formatScrollName(name, level)
    name = trim(name:gsub("%[", ""):gsub("Scroll]", ""))
    return string.format("%s (Level %s)", name, level)
end

-- Function to clean up spells in the ME system
local function cleanSpells()
    local spells = {}
    local items = me.listItems()

    -- Get the items in the ME system
    for _, item in ipairs(items) do  -- Use _ instead of i since i is unused, use item directly
        -- Check if the item is a spell scroll
        if item.name == "irons_spellbooks:scroll" then
            local nbt = item.components["irons_spellbooks:spell_container"].data

            -- Get the spell data from the NBT
            for _, data in ipairs(nbt) do
                local id = data.id
                local level = data.level
                local count = item.count
                
                -- If the spell is not in the list, add it
                if spells[id] == nil then
                    spells[id] = {
                        highest = level,
                        highest_count = count,
                        list = {}
                    }
                end

                -- Check if the spell is a higher level, if so, update the highest level
                if spells[id].highest < level then
                    spells[id].highest = level
                    spells[id].highest_count = count
                end

                -- Catalogue the spell
                table.insert(spells[id].list, {item = item, id = id, level = level, count = count})
            end
        end
    end


    -- Go through the spells and only keep the spells that are either the highest level or 1 below the highest level
    for id, spell in pairs(spells) do
        local keep_level = spell.highest
        local amount_of_highest_level = spell.highest_count
        
        -- Calculate the threshold level to keep
        local threshold = amount_of_highest_level <= 1 and keep_level - 1 or keep_level
        
        -- Process lower level spells for removal
        for _, data in ipairs(spell.list) do
            if data.level < threshold then
                print(textutils.formatTime(os.time())..": Removing spell: " .. formatScrollName(data.item.displayName, data.level.."/"..spell.highest))
                me.exportItemToPeripheral(data.item, trashPeripheral)
            end
        end
    end
end


-- Function to handle termination
local function handleTermination()
    running = false
    print(textutils.formatTime(os.time())..": Shutting down spell management system...")
end

-- Register termination handler
os.pullEvent = os.pullEventRaw  -- Prevent terminate event from being blocked

-- The main loop
while running do
    local success, error = pcall(cleanSpells)
    if not success then
        print(textutils.formatTime(os.time())..": Error in cleanSpells: " .. tostring(error))
    end
    
    -- Check for terminate event
    local timer = os.startTimer(check_interval)
    local event, param = os.pullEvent()
    if event == "terminate" then
        handleTermination()
    end
end