extends ActionLeaf

func is_goals_achieved(actor) -> bool:
	for i in range(3):
		for j in range(3):
			var board_idx = (i + 1) * 5 + (j + 1)
			var goal_idx = i * 3 + j
			if actor.goals[goal_idx] != -1 and actor.goals[goal_idx] != actor.playerboard[board_idx]:
				return false
			elif actor.goals[goal_idx] == -1 and actor.playerboard[board_idx] != -1:
				return false
	return true

func tick(actor: Node, blackboard: Blackboard) -> int:
	# Don't move if goals are achieved
	if is_goals_achieved(actor):
		return FAILURE

	# Get target from blackboard
	var target_pos = blackboard.get_value("move_target")
	if not target_pos:
		return FAILURE
		
	if actor.action_points <= 0:
		return FAILURE

	if not actor.is_bot == true and not actor.is_in_group("Bots"):
		return FAILURE

	# Execute movement
	if actor.is_within_movement_range(target_pos):
		if actor.is_bot == true:
			var path = actor.enhanced_gridmap.find_path(
				Vector2(actor.current_position), 
				Vector2(target_pos),
				0,
				false
			)
			if path.size() > 1:
				path.pop_front()
				actor.rpc("start_movement_along_path", path, false)
				actor.action_points -= 1
				blackboard.set_value("current_action", "moving")
				return SUCCESS
	
	return FAILURE
