-- parasite_compulsion_drive.lua
-- Uses CharacterDataComponent.mVelocity for directed movement
-- because ControlsComponent.enabled=false ignores button states.

local puppet = GetUpdatedEntityID()
local player_id = EntityGetParent(puppet)
if player_id == nil or player_id == 0 then
	EntityKill(puppet)
	return
end

if GlobalsGetValue("LN_COMPULSION_ACTIVE", "0") ~= "1" then
	EntityKill(puppet)
	return
end

local frame = GameGetFrameNum()
local end_frame = tonumber(GlobalsGetValue("LN_COMPULSION_END", "0")) or 0
local start_frame = tonumber(GlobalsGetValue("LN_COMPULSION_START", "0")) or 0

if frame >= end_frame or (start_frame > 0 and (frame - start_frame) > 60 * 60) then
	GlobalsSetValue("LN_COMPULSION_ACTIVE", "0")
	GlobalsSetValue("LN_COMPULSION_SOURCE", "")
	GlobalsSetValue("LN_COMPULSION_START", "0")
	local cc = EntityGetFirstComponentIncludingDisabled(player_id, "ControlsComponent")
	if cc then
		ComponentSetValue2(cc, "enabled", true)
	end
	for _, child in ipairs(EntityGetAllChildren(player_id) or {}) do
		if EntityGetName(child) == "ln_compulsion_puppet" then
			EntityKill(child)
		end
	end
	return
end

-- Abort if sex/birth scene starts
if EntityGetWithName("ln_sex_cooldown") ~= 0 then
	GlobalsSetValue("LN_COMPULSION_ACTIVE", "0")
	GlobalsSetValue("LN_COMPULSION_SOURCE", "")
	GlobalsSetValue("LN_COMPULSION_START", "0")
	EntityKill(puppet)
	return
end

-- Block wolf leash conflict
if GlobalsGetValue("LN_WOLF_BOND_ACTIVE", "0") == "1" then
	GlobalsSetValue("LN_COMPULSION_ACTIVE", "0")
	GlobalsSetValue("LN_COMPULSION_SOURCE", "")
	EntityKill(puppet)
	return
end

-- Lock controls (blocks keyboard input)
local cc = EntityGetFirstComponentIncludingDisabled(player_id, "ControlsComponent")
if cc then
	ComponentSetValue2(cc, "enabled", false)
end

local px, py = EntityGetTransform(player_id)

-- Find nearest visible enemy
local nearest = nil
local nearest_dist = 99999
for _, e in ipairs(EntityGetInRadiusWithTag(px, py, 250, "enemy") or {}) do
	local ex, ey = EntityGetTransform(e)
	if ex and ey then
		local dist = math.sqrt((ex - px) * (ex - px) + (ey - py) * (ey - py))
		if dist < nearest_dist then
			local hit = RaytraceSurfaces(px, py, ex, ey)
			if not hit then
				nearest = e
				nearest_dist = dist
			end
		end
	end
end

-- Direct velocity control (same as wolf leash and sex_scene.lua)
local cdc = EntityGetFirstComponent(player_id, "CharacterDataComponent")
if cdc then
	if nearest then
		local ex, ey = EntityGetTransform(nearest)
		local dx = ex - px
		local dy = ey - py
		local dist = math.sqrt(dx * dx + dy * dy)
		if dist > 5 then
			local nx = dx / dist
			local ny = dy / dist
			ComponentSetValue2(cdc, "mVelocity", nx * 50, ny * 50)
		else
			ComponentSetValue2(cdc, "mVelocity", 0, 0)
		end
	else
		-- No visible enemy — lock in place
		ComponentSetValue2(cdc, "mVelocity", 0, 0)
	end
end
