extends ConditionLeaf

func tick(actor: Node, blackboard: Blackboard) -> int:
	# Find a valid movement target
	var target_pos = find_valid_target(actor)
	if target_pos:
		# Store target in blackboard
		blackboard.set_value("move_target", target_pos)
		return SUCCESS
	return FAILURE

func find_valid_target(actor: Node) -> Vector2i:
	# Get random position in range
	var valid_positions = []
	
	for x in range(max(0, actor.current_position.x - actor.movement_range), 
				   min(actor.enhanced_gridmap.columns, actor.current_position.x + actor.movement_range + 1)):
		for z in range(max(0, actor.current_position.y - actor.movement_range), 
					  min(actor.enhanced_gridmap.rows, actor.current_position.y + actor.movement_range + 1)):
			var pos = Vector2i(x, z)
			if pos != actor.current_position and actor.is_within_movement_range(pos):
				if not actor.is_position_occupied(pos):
					valid_positions.append(pos)
	
	if valid_positions.size() > 0:
		return valid_positions[randi() % valid_positions.size()]
	return Vector2i(-1, -1)
