-- wolf_passivity.lua
-- AI stays ENABLED at all times (wolf walks/platforms naturally).
-- WANDER: zero creature_detection_range so wolf is blind, wanders freely.
-- APPROACH: restore detection range so wolf sees and chases the player.
-- Scene trigger fires naturally via start_sex.lua when wolf gets close enough.
-- Post-scene: detected via is_predator false edge → back to WANDER.

dofile_once("data/scripts/lib/utilities.lua")

local driver = GetUpdatedEntityID()
local wolf_id = EntityGetParent(driver)
if wolf_id == nil or wolf_id == 0 then
	EntityKill(driver)
	return
end

if GlobalsGetValue("LN_WOLF_BOND_ACTIVE", "0") ~= "1" then
	-- Restore full detection range on cleanup
	edit_component(wolf_id, "AnimalAIComponent", function(comp, vars)
		vars.creature_detection_range_x = 300
		vars.creature_detection_range_y = 300
	end)
	EntityKill(driver)
	return
end

local frame = GameGetFrameNum()

-- Read is_predator: false = post-scene cooldown
local genome = EntityGetFirstComponent(wolf_id, "GenomeDataComponent")
local is_predator = true
if genome then is_predator = ComponentGetValue2(genome, "is_predator") end

-- Detect true→false edge ONCE
local prev = GlobalsGetValue("LN_WOLF_WAS_PREDATOR", "1")
if not is_predator and prev == "1" then
	SetRandomSeed(frame, wolf_id + 7890)
	GlobalsSetValue("LN_WOLF_STATE", "wander")
	GlobalsSetValue("LN_WOLF_STATE_END", tostring(frame + Random(20, 35) * 60))
end
GlobalsSetValue("LN_WOLF_WAS_PREDATOR", is_predator and "1" or "0")

local state = GlobalsGetValue("LN_WOLF_STATE", "")
local state_end = tonumber(GlobalsGetValue("LN_WOLF_STATE_END", "0")) or 0

-- First init
if state == "" then
	SetRandomSeed(frame, wolf_id + 1111)
	state = "wander"
	GlobalsSetValue("LN_WOLF_STATE", state)
	GlobalsSetValue("LN_WOLF_STATE_END", tostring(frame + Random(15, 30) * 60))
	state_end = tonumber(GlobalsGetValue("LN_WOLF_STATE_END", "0"))
end

-- State transitions (only when wolf is ready to act)
if frame >= state_end and is_predator then
	if state == "wander" then
		state = "approach"
		GlobalsSetValue("LN_WOLF_STATE", "approach")
		GlobalsSetValue("LN_WOLF_STATE_END", tostring(frame + 12 * 60))
	elseif state == "approach" then
		-- Timed out without scene
		SetRandomSeed(frame, wolf_id + 2222)
		state = "wander"
		GlobalsSetValue("LN_WOLF_STATE", "wander")
		GlobalsSetValue("LN_WOLF_STATE_END", tostring(frame + Random(10, 20) * 60))
	end
end

-- Apply detection range based on state
edit_component(wolf_id, "AnimalAIComponent", function(comp, vars)
	if state == "wander" then
		-- Blind: wanders via natural pathfinding without targeting anything
		vars.creature_detection_range_x = 0
		vars.creature_detection_range_y = 0
	else
		-- Approach: full sight, charges toward player
		vars.creature_detection_range_x = 300
		vars.creature_detection_range_y = 300
	end
end)
