extends SceneTree

## Synthetic lifecycle, FIFO, ownership and timing regression for animated M2
## threaded scene loading.

const PIPELINE_SCRIPT := preload("res://src/render/m2/m2_animation_load_pipeline_state.gd")
const PIPELINE_PATH := "res://src/render/m2/m2_animation_load_pipeline_state.gd"
const OBSERVER_PATH := (
	"res://src/render/m2/m2_cached_animation_resource_observer.gd"
)
const RESOURCE_FINALIZER_PATH := (
	"res://src/render/m2/m2_animation_resource_finalizer.gd"
)
const LOADER_PATH := "res://src/scenes/streaming/streaming_world_loader.gd"


func _initialize() -> void:
	var failures: Array[String] = []
	_verify_validation_dedupe_and_order(failures)
	_verify_terminal_transition_and_fifo(failures)
	_verify_discard_metrics_clear_and_diagnostics(failures)
	_verify_ownership_boundaries(failures)
	var elapsed_milliseconds := _verify_bounded_timing(failures)
	if not failures.is_empty():
		for failure in failures:
			push_error("M2_ANIMATION_LOAD_PIPELINE_STATE: %s" % failure)
		quit(1)
		return
	print(
		"M2_ANIMATION_LOAD_PIPELINE_STATE PASS cases=11 iterations=100 elapsed_ms=%.3f"
		% elapsed_milliseconds
	)
	quit(0)


func _verify_validation_dedupe_and_order(failures: Array[String]) -> void:
	var pipeline: RefCounted = PIPELINE_SCRIPT.new()
	_expect_false(pipeline.call("remember_request", "", "res://a.glb"), "empty normalized path rejected", failures)
	_expect_false(pipeline.call("remember_request", "world/a.m2", ""), "empty resource path rejected", failures)
	_expect_true(pipeline.call("remember_request", "world/a.m2", "res://a.glb"), "first request accepted", failures)
	_expect_false(pipeline.call("remember_request", "world/a.m2", "res://duplicate.glb"), "duplicate request rejected", failures)
	_expect_true(pipeline.call("remember_request", "world/b.m2", "res://b.glb"), "second request accepted", failures)
	_expect_true(pipeline.call("has_request", "world/a.m2"), "request observable", failures)
	var records: Array[Dictionary] = pipeline.call("request_records_snapshot")
	_expect_equal(records.size(), 2, "request record count", failures)
	_expect_string_equal(String(records[0]["normalized"]), "world/a.m2", "request insertion order first", failures)
	_expect_string_equal(String(records[1]["normalized"]), "world/b.m2", "request insertion order second", failures)


func _verify_terminal_transition_and_fifo(failures: Array[String]) -> void:
	var pipeline: RefCounted = PIPELINE_SCRIPT.new()
	pipeline.call("remember_request", "world/a.m2", "res://a.glb")
	pipeline.call("remember_request", "world/b.m2", "res://b.glb")
	_expect_false(pipeline.call("complete_request", "world/missing.m2", 3), "unknown completion rejected", failures)
	_expect_true(pipeline.call("complete_request", "world/b.m2", 4), "second request completes first", failures)
	_expect_true(pipeline.call("complete_request", "world/a.m2", 3), "first request completes second", failures)
	_expect_false(pipeline.call("has_request", "world/a.m2"), "completed request removed", failures)
	_expect_equal(int(pipeline.call("pending_request_count")), 0, "all requests completed", failures)
	_expect_equal(int(pipeline.call("finalize_record_count")), 2, "two terminal records", failures)
	var first: Dictionary = pipeline.call("pop_finalize_record")
	var second: Dictionary = pipeline.call("pop_finalize_record")
	_expect_string_equal(String(first["normalized"]), "world/b.m2", "completion FIFO first", failures)
	_expect_equal(int(first["status"]), 4, "first opaque status retained", failures)
	_expect_string_equal(String(second["normalized"]), "world/a.m2", "completion FIFO second", failures)
	_expect_equal(int(second["status"]), 3, "second opaque status retained", failures)
	_expect_false(pipeline.call("has_finalize_record"), "finalize FIFO drained", failures)
	_expect_true((pipeline.call("pop_finalize_record") as Dictionary).is_empty(), "empty pop returns Dictionary", failures)


func _verify_discard_metrics_clear_and_diagnostics(failures: Array[String]) -> void:
	var pipeline: RefCounted = PIPELINE_SCRIPT.new()
	pipeline.call("remember_request", "world/a.m2", "res://a.glb")
	pipeline.call("remember_request", "world/b.m2", "res://b.glb")
	_expect_true(pipeline.call("discard_request", "world/a.m2"), "pending request discarded", failures)
	_expect_false(pipeline.call("discard_request", "world/a.m2"), "discard is idempotent", failures)
	pipeline.call("complete_request", "world/b.m2", 3)
	_expect_equal(int(pipeline.call("total_work_count")), 1, "total includes finalize only", failures)
	var snapshot: Dictionary = pipeline.call("diagnostic_snapshot")
	(snapshot["finalize_records"] as Array)[0]["path"] = "mutated"
	var fresh_snapshot: Dictionary = pipeline.call("diagnostic_snapshot")
	_expect_string_equal(String((fresh_snapshot["finalize_records"] as Array)[0]["path"]), "res://b.glb", "diagnostics detached", failures)
	pipeline.call("clear")
	pipeline.call("clear")
	_expect_equal(int(pipeline.call("total_work_count")), 0, "clear removes all work", failures)


func _verify_ownership_boundaries(failures: Array[String]) -> void:
	var pipeline_source := FileAccess.get_file_as_string(PIPELINE_PATH)
	var observer_source := FileAccess.get_file_as_string(OBSERVER_PATH)
	var resource_finalizer_source := FileAccess.get_file_as_string(
		RESOURCE_FINALIZER_PATH
	)
	var loader_source := FileAccess.get_file_as_string(LOADER_PATH)
	_expect_true(loader_source.contains("M2_ANIMATION_LOAD_PIPELINE_STATE_SCRIPT.new()"), "loader composes pipeline state", failures)
	_expect_false(loader_source.contains("var _m2_animation_load_requests:"), "legacy request field removed", failures)
	_expect_false(loader_source.contains("var _m2_animation_finalize_queue:"), "legacy finalize field removed", failures)
	_expect_equal(loader_source.count("_m2_animation_load_pipeline_state.total_work_count()"), 3, "three existing metrics delegate", failures)
	_expect_equal(loader_source.count("_m2_animation_load_pipeline_state.clear()"), 2, "two existing clear sites delegate", failures)
	_expect_true(
		observer_source.contains("ResourceLoader.load_threaded_request("),
		"cached observer owns request admission",
		failures
	)
	for retained_renderer_rule in [
		"ResourceLoader.load_threaded_get_status(resource_path)",
		"ResourceLoader.load_threaded_get(resource_path)",
		"RENDER_BUDGET_SCHEDULER_SCRIPT.M2_ANIMATION_FINALIZE",
		"\"adopt_animated_prototype\"",
		"\"mark_animation_static\"",
	]:
		_expect_true(
			(loader_source + resource_finalizer_source).contains(retained_renderer_rule),
			"renderer retains %s" % retained_renderer_rule,
			failures
		)
	for forbidden_dependency in [
		"ResourceLoader.",
		"WorkerThreadPool.",
		"Node3D",
		"PackedScene",
		": Mesh",
		"_m2_prototype_cache_state",
		"_render_budget_scheduler",
	]:
		_expect_false(pipeline_source.contains(forbidden_dependency), "pipeline omits %s ownership" % forbidden_dependency, failures)


func _verify_bounded_timing(failures: Array[String]) -> float:
	var pipeline: RefCounted = PIPELINE_SCRIPT.new()
	var started_microseconds := Time.get_ticks_usec()
	for _iteration in range(100):
		for path_index in range(256):
			pipeline.call("remember_request", "world/model_%d.m2" % path_index, "res://model_%d.glb" % path_index)
		for path_index in range(256):
			pipeline.call("complete_request", "world/model_%d.m2" % path_index, 3)
		while pipeline.call("has_finalize_record"):
			pipeline.call("pop_finalize_record")
		pipeline.call("clear")
	var elapsed_milliseconds := float(Time.get_ticks_usec() - started_microseconds) / 1000.0
	_expect_true(elapsed_milliseconds < 1000.0, "100 by 256 transitions under 1 second", failures)
	return elapsed_milliseconds


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_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])
