extends SceneTree

## Synthetic batch duplication, render-property, playback, ownership-boundary
## and bounded-timing regression for animated M2 instance materialization.

const MATERIALIZER_SCRIPT := preload(
	"res://src/render/m2/m2_animated_instance_materializer.gd"
)
const NATIVE_ANIMATOR_SCRIPT := preload("res://src/scenes/streaming/m2_native_animator.gd")
const MATERIALIZER_PATH := "res://src/render/m2/m2_animated_instance_materializer.gd"
const LOADER_PATH := "res://src/scenes/streaming/streaming_world_loader.gd"


func _initialize() -> void:
	var failures: Array[String] = []
	_verify_batch_contract(failures)
	_verify_invalid_inputs(failures)
	_verify_ownership_boundaries(failures)
	var elapsed_milliseconds := _verify_bounded_timing(failures)
	if not failures.is_empty():
		for failure in failures:
			push_error("M2_ANIMATED_INSTANCE_MATERIALIZER: %s" % failure)
		quit(1)
		return
	print(
		"M2_ANIMATED_INSTANCE_MATERIALIZER PASS cases=12 instances=1000 elapsed_ms=%.3f"
		% elapsed_milliseconds
	)
	quit(0)


func _verify_batch_contract(failures: Array[String]) -> void:
	var materializer = MATERIALIZER_SCRIPT.new()
	var parent_root := Node3D.new()
	get_root().add_child(parent_root)
	var prototype := _make_animated_prototype()
	var transforms: Array = [
		Transform3D(Basis.IDENTITY, Vector3.ZERO),
		Transform3D(Basis.IDENTITY, Vector3(1.0, 2.0, 3.0)),
		Transform3D(Basis.IDENTITY, Vector3(4.0, 5.0, 6.0)),
	]
	var result: Dictionary = materializer.materialize_batch(
		parent_root,
		"World\\Doodads\\AnimatedTree.m2",
		prototype,
		transforms,
		1,
		2,
		7,
		345.0,
		16.0,
		false,
		NATIVE_ANIMATOR_SCRIPT,
		true
	)
	_expect_false(result.is_empty(), "valid batch returned", failures)
	var batch_root: Node3D = result.get("batch_root", null)
	_expect_same(batch_root.get_parent(), parent_root, "batch attached to supplied parent", failures)
	_expect_string_equal(batch_root.name, "AnimatedTree_anim_7", "batch name", failures)
	_expect_equal(batch_root.get_child_count(), 2, "ordered duplicate count", failures)
	for batch_offset in 2:
		var instance := batch_root.get_child(batch_offset) as Node3D
		var instance_index := batch_offset + 1
		_expect_string_equal(instance.name, "AnimatedTree_%d" % instance_index, "instance name", failures)
		_expect_true(instance.transform == transforms[instance_index], "instance transform", failures)
		var geometry := instance.get_node("Branch/Geometry") as GeometryInstance3D
		_expect_float_equal(geometry.visibility_range_end, 345.0, "recursive visibility end", failures)
		_expect_float_equal(geometry.visibility_range_end_margin, 16.0, "recursive visibility margin", failures)
		_expect_equal(
			geometry.cast_shadow,
			GeometryInstance3D.SHADOW_CASTING_SETTING_OFF,
			"recursive shadow mode",
			failures
		)
		var player := instance.get_node("AnimationPlayer") as AnimationPlayer
		_expect_string_equal(player.current_animation, "Stand", "playback started", failures)
		var animator: Node = instance.get_node("Branch/NativeAnimator")
		_expect_same(
			animator.bones,
			prototype.get_node("Branch/NativeAnimator").bones,
			"native fields copied by reference",
			failures
		)

	var diagnostic_entries: Array = result.get("native_diagnostics", [])
	_expect_equal(diagnostic_entries.size(), 2, "one native diagnostic per instance", failures)
	for diagnostic_offset in diagnostic_entries.size():
		var entry: Dictionary = diagnostic_entries[diagnostic_offset]
		_expect_equal(
			int(entry.get("instance_index", -1)),
			diagnostic_offset + 1,
			"diagnostic index",
			failures
		)
		_expect_equal(
			int((entry.get("state", {}) as Dictionary).get("bones", 0)),
			1,
			"diagnostic state",
			failures
		)

	var source_geometry := prototype.get_node("Branch/Geometry") as GeometryInstance3D
	_expect_float_equal(source_geometry.visibility_range_end, 0.0, "prototype render state unchanged", failures)
	prototype.free()
	parent_root.free()


func _verify_invalid_inputs(failures: Array[String]) -> void:
	var materializer = MATERIALIZER_SCRIPT.new()
	var prototype := Node3D.new()
	var parent_root := Node3D.new()
	_expect_true(
		materializer.materialize_batch(
			null, "a.m2", prototype, [Transform3D.IDENTITY], 0, 1, 0,
			0.0, 0.0, true, NATIVE_ANIMATOR_SCRIPT, false
		).is_empty(),
		"null parent rejected",
		failures
	)
	_expect_true(
		materializer.materialize_batch(
			parent_root, "a.m2", prototype, [], 0, 1, 0,
			0.0, 0.0, true, NATIVE_ANIMATOR_SCRIPT, false
		).is_empty(),
		"empty transforms rejected",
		failures
	)
	_expect_true(
		materializer.materialize_batch(
			parent_root, "a.m2", prototype, [Transform3D.IDENTITY], 0, 0, 0,
			0.0, 0.0, true, NATIVE_ANIMATOR_SCRIPT, false
		).is_empty(),
		"zero count rejected",
		failures
	)
	_expect_equal(parent_root.get_child_count(), 0, "invalid input has no attachment", failures)
	prototype.free()
	parent_root.free()


func _verify_ownership_boundaries(failures: Array[String]) -> void:
	var materializer_source := FileAccess.get_file_as_string(MATERIALIZER_PATH)
	var loader_source := FileAccess.get_file_as_string(LOADER_PATH)
	_expect_true(
		loader_source.contains("M2_ANIMATED_INSTANCE_MATERIALIZER_SCRIPT.new()"),
		"loader composes materializer",
		failures
	)
	_expect_equal(
		loader_source.count("_m2_animated_instance_materializer.materialize_batch("),
		1,
		"loader delegates once",
		failures
	)
	for retained_loader_rule in [
		"_set_editor_owner_recursive(batch_root)",
		"M2_NATIVE_ANIMATOR path=%s instance=%d",
		"_normalize_m2_rel_path(rel_path)",
	]:
		_expect_true(
			loader_source.contains(retained_loader_rule),
			"loader retains %s" % retained_loader_rule,
			failures
		)
	for removed_loader_rule in [
		"prototype.duplicate(Node.DUPLICATE_SIGNALS | Node.DUPLICATE_GROUPS | Node.DUPLICATE_SCRIPTS)",
		"_m2_animation_playback_controller",
	]:
		_expect_false(
			loader_source.contains(removed_loader_rule),
			"loader releases %s" % removed_loader_rule,
			failures
		)
	for required_materializer_rule in [
		"Node.DUPLICATE_SIGNALS | Node.DUPLICATE_GROUPS | Node.DUPLICATE_SCRIPTS",
		"_animation_playback_controller.copy_native_animator_data(",
		"_animation_playback_controller.start_instance_playback(",
		"m2_parent_root.add_child(batch_root)",
	]:
		_expect_true(
			materializer_source.contains(required_materializer_rule),
			"materializer owns %s" % required_materializer_rule,
			failures
		)
	for forbidden_dependency in [
		"ResourceLoader.",
		"FileAccess.",
		"WorkerThreadPool.",
		"MultiMesh",
		".owner =",
		"_m2_build_jobs",
		"_render_budget_scheduler",
	]:
		_expect_false(
			materializer_source.contains(forbidden_dependency),
			"materializer omits %s ownership" % forbidden_dependency,
			failures
		)


func _verify_bounded_timing(failures: Array[String]) -> float:
	var materializer = MATERIALIZER_SCRIPT.new()
	var parent_root := Node3D.new()
	get_root().add_child(parent_root)
	var prototype := Node3D.new()
	var transforms: Array = []
	for instance_index in 1000:
		transforms.append(
			Transform3D(Basis.IDENTITY, Vector3(float(instance_index), 0.0, 0.0))
		)
	var started_microseconds := Time.get_ticks_usec()
	var result: Dictionary = materializer.materialize_batch(
		parent_root, "world/timing.m2", prototype, transforms, 0, 1000, 1,
		0.0, 0.0, true, NATIVE_ANIMATOR_SCRIPT, false
	)
	var elapsed_milliseconds := float(Time.get_ticks_usec() - started_microseconds) / 1000.0
	var batch_root := result.get("batch_root", null) as Node3D
	_expect_equal(batch_root.get_child_count(), 1000, "timing batch complete", failures)
	_expect_true(elapsed_milliseconds < 1000.0, "1000 instances under 1 second", failures)
	prototype.free()
	parent_root.free()
	return elapsed_milliseconds


func _make_animated_prototype() -> Node3D:
	var prototype := Node3D.new()
	var branch := Node3D.new()
	branch.name = "Branch"
	prototype.add_child(branch)
	var geometry := MeshInstance3D.new()
	geometry.name = "Geometry"
	branch.add_child(geometry)
	var native_animator: Node = NATIVE_ANIMATOR_SCRIPT.new()
	native_animator.name = "NativeAnimator"
	native_animator.mesh_instance_path = NodePath("../Geometry")
	native_animator.bones = [{"parent": -1}]
	native_animator.surfaces = [{"vertices": PackedVector3Array()}]
	native_animator.animation_length = 8.0
	branch.add_child(native_animator)
	var player := AnimationPlayer.new()
	player.name = "AnimationPlayer"
	var library := AnimationLibrary.new()
	var stand := Animation.new()
	stand.length = 2.0
	library.add_animation("Stand", stand)
	player.add_animation_library("", library)
	prototype.add_child(player)
	return prototype


func _expect_true(condition: bool, label: String, failures: Array[String]) -> void:
	if not condition:
		failures.append(label)


func _expect_false(condition: bool, label: String, failures: Array[String]) -> void:
	_expect_true(not condition, label, failures)


func _expect_equal(actual: int, expected: int, label: String, failures: Array[String]) -> void:
	if actual != expected:
		failures.append("%s expected=%d actual=%d" % [label, expected, actual])


func _expect_float_equal(actual: float, expected: float, label: String, failures: Array[String]) -> void:
	if not is_equal_approx(actual, expected):
		failures.append("%s expected=%.6f actual=%.6f" % [label, expected, actual])


func _expect_string_equal(actual: String, expected: String, label: String, failures: Array[String]) -> void:
	if actual != expected:
		failures.append("%s expected=%s actual=%s" % [label, expected, actual])


func _expect_same(actual: Variant, expected: Variant, label: String, failures: Array[String]) -> void:
	if not is_same(actual, expected):
		failures.append(label)
