-- @author DoomTero 2026

local function banditsAvailable()
	return Bandit ~= nil and BanditCustom ~= nil and BanditBrain ~= nil
end

local function isFriendlyBandit(obj)
	if not banditsAvailable() then return false end
	if not instanceof(obj, "IsoZombie") then return false end
	if not obj:getVariableBoolean("Bandit") then return false end
	if obj:isDead() then return false end
	if Bandit.IsHostile and Bandit.IsHostile(obj) then return false end
	return true
end

local function findOnTilesAndNeighbors(worldobjects, predicate)
	for i = 1, #worldobjects do
		local obj = worldobjects[i]
		if predicate(obj) then return obj end
	end
	for i = 1, #worldobjects do
		local obj = worldobjects[i]
		local sq = obj and obj.getSquare and obj:getSquare()
		local cell = sq and sq:getCell()
		if sq and cell then
			local x, y, z = sq:getX(), sq:getY(), sq:getZ()
			for dx = -1, 1 do
				for dy = -1, 1 do
					local s = cell:getGridSquare(x + dx, y + dy, z)
					local moving = s and s:getMovingObjects()
					if moving then
						for j = 0, moving:size() - 1 do
							local m = moving:get(j)
							if predicate(m) then return m end
						end
					end
				end
			end
		end
	end
	return nil
end

local function findFriendlyBandit(worldobjects)
	return findOnTilesAndNeighbors(worldobjects, isFriendlyBandit)
end

local function onAskForSex(playerObj, target)
	if playerObj.setHaloNote then
		playerObj:setHaloNote("ZR: Friendly-bandit scenes not yet authored")
	end
end

local function onFillWorldObjectContextMenu(playerIndex, context, worldobjects, test)
	if test == true then return end

	local playerObj = getSpecificPlayer(playerIndex)
	if not playerObj then return end

	if SandboxVars and SandboxVars.ZomboRut
		and SandboxVars.ZomboRut.enableMod == false
	then
		return
	end

	if playerObj:isDraggingCorpse() then return end

	if not banditsAvailable() then return end

	local target = findFriendlyBandit(worldobjects)
	if not target then return end

	context:addOption("ZR: Ask for Sex", playerObj, function()
		onAskForSex(playerObj, target)
	end)
end

Events.OnFillWorldObjectContextMenu.Add(onFillWorldObjectContextMenu)
