CCCPaste

Irons Spell Books scroll clean up

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.getItems()
    local itemsToTrash = {}

    -- Scan all items and track highest level per spell ID
    for _, item in ipairs(items) do
        if item.name == "irons_spellbooks:scroll" then
            local nbt = item.components["irons_spellbooks:spell_container"].data
            -- Since there's only one spell per scroll, take the first (and only) entry
            local data = nbt[1]
            if data then
                local id = data.id
                local level = data.level
                if not spells[id] or spells[id].highest < level then
                    spells[id] = {highest = level}
                end
                -- Mark for potential trashing if not the highest
                table.insert(itemsToTrash, {item = item, id = id, level = level})
            end
        end
    end

    -- Now, trash items that are not the highest level for their spell ID
    for _, trashData in ipairs(itemsToTrash) do
        local spell = spells[trashData.id]
        if trashData.level < spell.highest then
            print(textutils.formatTime(os.time())..": Removing spell: " .. formatScrollName(trashData.item.displayName, trashData.level .. "/" .. spell.highest))
            me.exportItem(trashData.item, trashPeripheral)
        end
    end
end


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

-- Check for ME bridge
if not me then
    error("ME Bridge peripheral not found!")
end

-- Initial cleanup
print(textutils.formatTime(os.time())..": Performing initial spell cleanup...")
local success, err = pcall(cleanSpells)
if not success then
    print(textutils.formatTime(os.time())..": Initial error in cleanSpells: " .. tostring(err))
end

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