local BC = require("BC/Helpers")
local ModData = require("BC/ModData")

local function dlog(msg)
    BC.log(msg)
end

-- --- Helper: snapshot inventory by object identity (fast and reliable in Lua)
local function _snapshotInventory(inv)
    local seen = {}
    if not inv then return seen end

    local items = inv.getItems and inv:getItems() or nil
    if not items then return seen end

    for i = 0, items:size() - 1 do
        local it = items:get(i)
        if it then
            seen[it] = true
        end
    end
    return seen
end

-- ============================================================
-- Patch: wrap ButcheringUtil.giveMeatModified
-- ============================================================
if ButcheringUtil and ButcheringUtil.giveMeatModified then
    local _vanilla_giveMeatModified = ButcheringUtil.giveMeatModified

    ButcheringUtil.giveMeatModified = function(meatDef, nb, player, meatRatio, carcass, fromGround, rotten, deathAge)
        -- Server-authoritative stamping only.
        -- If this wrapper is running client-side, do not mutate item state.
        if isClient and isClient() and not (isServer and isServer()) then
            return _vanilla_giveMeatModified(meatDef, nb, player, meatRatio, carcass, fromGround, rotten, deathAge)
        end

        local inv = player and player.getInventory and player:getInventory() or nil

        local before = _snapshotInventory(inv)
        local text = _vanilla_giveMeatModified(meatDef, nb, player, meatRatio, carcass, fromGround, rotten, deathAge)

        -- If we have no inventory, nothing to stamp.
        if not inv then
            return text
        end

        local items = inv.getItems and inv:getItems() or nil
        if not items then
            return text
        end

        local stamped = 0
        local discovered = 0

        for i = 0, items:size() - 1 do
            local item = items:get(i)

            -- New item since before snapshot?
            if item and (not before[item]) and BC.isButcheredMeat(item) then
                discovered = discovered + 1
                local token = BC.getQualityToken(item)
                if token then
                    ModData.updateButcheredMeat(item, token)
                    if ModData.getMeatQuality(item) then
                        syncItemModData(player, item)
                        stamped = stamped + 1
                    end
                else
                    dlog("butcher meat candidate had no quality match")
                end
            end
        end

        dlog(tostring(discovered) .. " meat(s) discovered, " .. tostring(stamped) .. " stamped")

        return text
    end
else
    -- ButcheringUtil not loaded yet; ensure your BC bootstrap requires this patch after vanilla shared defs load.
    -- Intentionally no hard error.
end