local kobold_x, kobold_y = EntityGetTransform(GetUpdatedEntityID())
local close_enemies = EntityGetInRadiusWithTag(kobold_x, kobold_y, 10, "enemy")

if #close_enemies > 0 then
	local attacker = nil

	-- prevent kobolds detecting themselves as enemies which won't trigger scene start
	for _, enemy in ipairs(close_enemies) do
		if EntityGetName(enemy) ~= "$animal_kobold" then
			attacker = enemy
			break
		end
	end

	if attacker ~= nil then
		local no_cooldown = true

		for _, ch in ipairs(EntityGetAllChildren(GetUpdatedEntityID()) or {}) do
			if EntityGetName(ch) == "ln_sex_cooldown" then
				no_cooldown = false
				break
			end
		end

		-- is_predator check for enemy works like sex cooldown for enemies, they have it set to false for some time after sex
		if no_cooldown == true and
		ComponentGetValue2(EntityGetFirstComponent(GetUpdatedEntityID(), "DamageModelComponent"), "is_on_fire") == false and
		ComponentGetValue2(EntityGetFirstComponent(GetUpdatedEntityID(), "DamageModelComponent"), "mAirAreWeInWater") == false and
		ComponentGetValue2(EntityGetFirstComponent(attacker, "DamageModelComponent"), "is_on_fire") == false and
		ComponentGetValue2(EntityGetFirstComponent(attacker, "GenomeDataComponent"), "is_predator") == true and
		GameGetGameEffect(attacker, "CHARM") == 0 and
		GameGetGameEffect(attacker, "FROZEN") == 0 and
		GameGetGameEffect(attacker, "ELECTROCUTION") == 0 then

			-- "data/enemies_gfx/longleg.xml" -> "longleg"
			local enemy_name = ComponentGetValue2(EntityGetFirstComponent(attacker, "SpriteComponent"), "image_file"):match("([^/]+)%.xml$")

			if ModTextFileGetContent("mods/lewd_noita/files/sex_gfx/" .. enemy_name .. ".xml") ~= nil then
				local sex_scene = EntityCreateNew(enemy_name)

				local enemy_x, enemy_y = EntityGetTransform(attacker)

				-- whether scene should look left or right based on enemy approach
				if enemy_x < kobold_x then
					EntitySetTransform(sex_scene, enemy_x, enemy_y, 0, 1, 1)
				else
					EntitySetTransform(sex_scene, enemy_x, enemy_y, 0, -1, 1)
				end

				-- those two scenes can get wrong direction so it should always be default
				if enemy_name == "tentacle_trap_left" or enemy_name == "tentacle_trap_right" then
					EntitySetTransform(sex_scene, enemy_x, enemy_y, 0, 1, 1)
				end

				EntityAddChild(sex_scene, GetUpdatedEntityID())

				EntityAddComponent2(sex_scene, "LuaComponent", {
					script_source_file="mods/lewd_noita/files/sex_logic/sex_scene.lua"
				})

				-- those go inside kobold and worm keeps biting by its worm component so they should be killed
				if enemy_name == "lurker" or
				enemy_name == "maggot_1" or
				enemy_name == "maggot_2" or
				enemy_name == "maggot_3" or
				enemy_name == "maggot_4" or
				enemy_name == "miniblob" or
				enemy_name == "worm_tiny_head" or
				enemy_name == "tentacle_vase_blue" or
				enemy_name == "tentacle_vase_pink" then
					EntityKill(attacker)
				else
					EntityAddChild(sex_scene, attacker)
				end
			end
		end
	end
end