extends SceneTree

const M2_UNIQUE_PLACEMENT_REGISTRY := preload(
	"res://src/render/m2/m2_unique_placement_registry.gd"
)

var _failures := 0


func _initialize() -> void:
	var registry: RefCounted = M2_UNIQUE_PLACEMENT_REGISTRY.new()
	var placement := {
		"name_id": 0,
		"unique_id": 11785,
		"pos": Vector3.ZERO,
		"rot": Vector3.ZERO,
		"scale": 1.0,
	}

	var first: Dictionary = registry.call("reserve", "30_49", [placement])
	_expect((first.get("placements", []) as Array).size() == 1, "first tile should reserve unique M2 placement")
	_expect((first.get("unique_keys", []) as Array).has("uid:11785"), "first tile should own uid:11785")
	_expect((first.get("skipped_unique_keys", []) as Array).is_empty(), "first tile should not skip uid:11785")

	var duplicate: Dictionary = registry.call("reserve", "31_49", [placement])
	_expect((duplicate.get("placements", []) as Array).is_empty(), "second tile should skip duplicate uid:11785")
	_expect((duplicate.get("skipped_unique_keys", []) as Array).has("uid:11785"), "second tile should remember skipped uid:11785")

	registry.call("release", "30_49", ["uid:11785"])
	var after_release: Dictionary = registry.call("reserve", "31_49", [placement])
	_expect((after_release.get("placements", []) as Array).size() == 1, "second tile should reserve uid:11785 after owner release")
	_expect((after_release.get("unique_keys", []) as Array).has("uid:11785"), "second tile should own uid:11785 after release")

	var same_tile_registry: RefCounted = M2_UNIQUE_PLACEMENT_REGISTRY.new()
	var same_tile_duplicate: Dictionary = same_tile_registry.call("reserve", "31_49", [placement, placement])
	_expect((same_tile_duplicate.get("placements", []) as Array).size() == 1, "same tile should keep only one copy of duplicate uid:11785")

	if _failures > 0:
		push_error("M2 unique dedupe verification failed: %d issue(s)" % _failures)
		quit(1)
		return
	print("M2 unique dedupe verification passed.")
	quit(0)


func _expect(condition: bool, message: String) -> void:
	if condition:
		return
	_failures += 1
	push_error(message)
