extends ActionLeaf

func is_goals_achieved(actor) -> bool:
	# Check only central 3x3 area of playerboard against goals
	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
				
			# Also check outside the goal area
			if i == 0 or i == 4 or j == 0 or j == 4:
				if actor.playerboard[i * 5 + j] != -1:
					return false
	
	return true

func tick(actor: Node, blackboard: Blackboard) -> int:
	var put_position = blackboard.get_value("put_position")
	var put_slot = blackboard.get_value("put_slot")
	
	if not put_position or put_slot == -1:
		return FAILURE
		
	# Check if we still have the item and AP
	if actor.action_points <= 0 or actor.playerboard[put_slot] == -1:
		return FAILURE
		
	# Check if target position is still empty
	var cell = Vector3i(put_position.x, 1, put_position.y)
	if actor.enhanced_gridmap.get_cell_item(cell) != -1:
		return FAILURE
		
	# Execute put
	var item = actor.playerboard[put_slot]
	if actor.is_multiplayer_authority():
		actor.rpc("sync_grid_item", cell.x, cell.y, cell.z, item)
		actor.playerboard[put_slot] = -1
		actor.rpc("sync_playerboard", actor.playerboard)
		actor.has_performed_action = true
		actor.action_points -= 1
	
	return SUCCESS
