2D camera scrolling based on TileMap

I am making a 2D top-down game and want the camera to follow the player, so I made the camera a child of the Player node.

However, the camera should not follow the player if the level tilemap is smaller than the viewport. Similarly, the camera should not move vertically if the tilemap is wide but not tall, and it should not move horizontally if the tilemap is tall but not wide.

This code will follow the player on large levels and snap the camera in place for small levels. When scrolling, the camera moves slightly past the tilemap bounds.

func set_camera_limits():
	var map_limits = _tilemap.get_used_rect()
	var map_cellsize = _tilemap.CELL_SIZE
	
	var viewport_limits = get_viewport_rect()
	
	if Vector2i(viewport_limits.size) > (map_limits.size * map_cellsize):
		print("level smaller than camera")
		$Camera2D.offset = Vector2i(128, -128)
		$Camera2D.limit_left = map_limits.position.x * map_cellsize.x
		$Camera2D.limit_right = map_limits.end.x * map_cellsize.x
		$Camera2D.limit_top = map_limits.position.y * map_cellsize.y
		$Camera2D.limit_bottom = map_limits.end.y * map_cellsize.y
	else:
		print("level bigger than camera")
		$Camera2D.limit_left = map_limits.position.x * map_cellsize.x - 128
		$Camera2D.limit_right = map_limits.end.x * map_cellsize.x + 128
		$Camera2D.limit_top = map_limits.position.y * map_cellsize.y - 128
		$Camera2D.limit_bottom = map_limits.end.y * map_cellsize.y + 128
	
	var _big_horiz = viewport_limits.size.x < (map_limits.size.x * map_cellsize.x)
	var _big_vert = viewport_limits.size.y < (map_limits.size.y * map_cellsize.y)
	
	if _big_horiz and _big_vert:
		print("level bigger than camera in all directions")
	elif _big_horiz:
		print("level bigger than camera horizontally")
		$Camera2D.offset.y = -128
		$Camera2D.limit_top = map_limits.position.y * map_cellsize.y
		$Camera2D.limit_bottom = map_limits.end.y * map_cellsize.y
	elif _big_vert:
		print("level bigger than camera vertically")
		$Camera2D.offset.x = 128
		$Camera2D.limit_left = map_limits.position.x * map_cellsize.x
		$Camera2D.limit_right = map_limits.end.x * map_cellsize.x

I couldn’t find a better solution than this, but I am open to suggestions for improvement.

Have you seen Phantom Camera?