extends SceneTree

var failures: Array[String] = []


func _initialize() -> void:
	call_deferred("_run")


func _run() -> void:
	await _test_deterministic_continuation()
	await _test_resource_state_round_trip()
	_test_legacy_npc_migration()
	_test_legacy_resource_migration()
	_test_legacy_world_storage_migration()
	_test_previous_world_event_migration()
	_test_schema_rejection()

	if failures.is_empty():
		print("[TEST] Simulation state serialization passed")
		quit(0)
		return

	for failure in failures:
		push_error("[TEST] " + failure)
	quit(1)


func _test_deterministic_continuation() -> void:
	var uninterrupted := _create_manager(91234)
	_advance_scenario(uninterrupted, 24)
	uninterrupted.clock.advance(0.5)
	_advance_scenario(uninterrupted, 24)
	var uninterrupted_checksum: String = uninterrupted.get_state_checksum()

	var before_save := _create_manager(91234)
	_advance_scenario(before_save, 24)
	before_save.clock.advance(0.5)
	var saved_json: String = before_save.serialize_state()

	var restored := _create_manager(1)
	_check(
		restored.restore_state_from_json(saved_json),
		"A valid versioned state should restore into a fresh manager"
	)
	_check(restored.tick_count == 24, "Tick count should survive restoration")
	_check(
		is_equal_approx(restored.clock.accumulator, 0.5),
		"Clock remainder should survive restoration"
	)
	_advance_scenario(restored, 24)
	var restored_checksum: String = restored.get_state_checksum()
	if restored_checksum != uninterrupted_checksum:
		print(
			"[TEST] uninterrupted=",
			uninterrupted.serialize_state(),
			"\n[TEST] restored=",
			restored.serialize_state()
		)
	_check(
		restored_checksum == uninterrupted_checksum,
		"Restored simulation should match uninterrupted deterministic continuation"
	)

	uninterrupted.free()
	before_save.free()
	restored.free()


func _test_resource_state_round_trip() -> void:
	var resource: ResourceNode = load("res://world/resource_nodes/ResourceNode.tscn").instantiate()
	resource.node_id = &"SerializationTestBerry"
	resource.initial_amount = 9.0
	resource.yield_per_action = 2.0
	root.add_child(resource)
	await process_frame

	var manager := _create_manager(77)
	_check(
		manager.register_resource_node(resource),
		"Resource presentation should bind to simulation authority"
	)
	var resource_state: ResourceStateRecord = manager.get_resource_state(resource.node_id)
	_check(resource_state.reserve(42), "Resource should accept the test reservation")
	resource_state.extract()
	var saved_json: String = manager.serialize_state()
	resource.free()

	_check(
		is_equal_approx(resource_state.get_amount_remaining(), 7.0),
		"Resource state should survive without its presentation node"
	)
	resource_state.extract(5.0)
	resource_state.release(42)
	resource_state.set_enabled(false)

	_check(
		manager.restore_state_from_json(saved_json),
		"Unloaded resource state should restore with the simulation record"
	)
	resource_state = manager.get_resource_state(&"SerializationTestBerry")
	_check(
		is_equal_approx(resource_state.get_amount_remaining(), 7.0),
		"Resource amount should round-trip"
	)
	_check(resource_state.get_reserved_by() == 42, "Resource reservation should round-trip")
	_check(resource_state.is_enabled(), "Resource enabled state should round-trip")

	var rebound: ResourceNode = load("res://world/resource_nodes/ResourceNode.tscn").instantiate()
	rebound.node_id = &"SerializationTestBerry"
	rebound.initial_amount = 999.0
	root.add_child(rebound)
	await process_frame
	_check(
		rebound.state == resource_state,
		"Reloaded presentation should bind to the existing authoritative record"
	)
	_check(
		is_equal_approx(rebound.get_amount_remaining(), 7.0),
		"Reloaded presentation must not overwrite authoritative amount"
	)

	manager.free()
	rebound.free()


func _test_schema_rejection() -> void:
	var unsupported := JSON.stringify(
		{"schema": SimulationStateRecord.SCHEMA_NAME, "schema_version": 999}
	)
	_check(
		SimulationStateRecord.from_json(unsupported) == null,
		"Unsupported schema versions should be rejected"
	)
	_check(SimulationStateRecord.from_json("[]") == null, "Non-record JSON should be rejected")


func _test_legacy_resource_migration() -> void:
	var migrated := ResourceStateRecord.from_dictionary(
		{
			"schema_version": 1,
			"node_id": "legacy_tree",
			"amount_remaining": 6.0,
			"reserved_by": 12,
			"enabled": true
		}
	)
	_check(migrated != null, "ResourceStateRecord v1 should migrate explicitly")
	if migrated == null:
		return
	_check(
		migrated.data["schema_version"] == ResourceStateRecord.SCHEMA_VERSION,
		"Migrated resource state should use the current nested schema"
	)
	_check(
		is_equal_approx(migrated.get_amount_remaining(), 6.0) and migrated.get_reserved_by() == 12,
		"Resource migration should preserve mutable authority"
	)


func _test_legacy_npc_migration() -> void:
	var npc := SimNPC.new(88, "LegacyNPC", SimulationIds.PROFESSION_FARMER, 5.0, 5.0)
	var legacy_data := NPCStateRecord.capture(npc).to_dictionary()
	legacy_data["schema_version"] = NPCStateRecord.LEGACY_SCHEMA_VERSION
	legacy_data.erase("travel_target_position")
	legacy_data.erase("has_travel_target")
	var migrated := NPCStateRecord.from_dictionary(legacy_data)
	_check(migrated != null, "NPCStateRecord v1 should migrate explicitly")
	if migrated == null:
		return
	_check(
		not bool(migrated.data["has_travel_target"]),
		"Legacy NPC migration should not invent an active travel target"
	)


func _test_legacy_world_storage_migration() -> void:
	var manager := _create_manager(55)
	var legacy_data: Dictionary = manager.create_state_record().to_dictionary()
	legacy_data["schema_version"] = SimulationStateRecord.LEGACY_SCHEMA_VERSION
	legacy_data.erase("storages")
	var migrated := SimulationStateRecord.from_dictionary(legacy_data)
	_check(migrated != null, "World schema v1 should migrate pantry storage")
	if migrated != null:
		_check(
			(
				migrated.storages.size() == 1
				and is_equal_approx(
					migrated.storages[0].get_amount(SimulationIds.RESOURCE_FOOD),
					manager.village.food
				)
			),
			"World migration should preserve legacy village food in pantry"
		)
	manager.free()


func _test_previous_world_event_migration() -> void:
	var manager := _create_manager(56)
	var previous_data: Dictionary = manager.create_state_record().to_dictionary()
	previous_data["schema_version"] = (SimulationStateRecord.PREVIOUS_SCHEMA_VERSION)
	previous_data.erase("economic_events")
	previous_data["simulation"].erase("next_event_id")
	var migrated := SimulationStateRecord.from_dictionary(previous_data)
	_check(migrated != null, "World schema v2 should add an empty event stream")
	if migrated != null:
		_check(
			migrated.economic_events.is_empty() and int(migrated.simulation["next_event_id"]) == 0,
			"World v2 migration should initialize deterministic event identity"
		)
	manager.free()


func _create_manager(seed_value: int) -> Node:
	var manager: Node = load("res://simulation/SimulationManager.gd").new()
	manager.simulation_seed = seed_value
	manager.debug_logs = false
	root.add_child(manager)
	manager.set_process(false)
	return manager


func _advance_scenario(manager: Node, steps: int) -> void:
	for step in steps:
		manager.simulate_tick()
		for npc in manager.npcs:
			manager.get_wander_offset(npc.id)
			if npc.task_state == SimNPC.TASK_STATE_TRAVELING:
				manager.notify_npc_arrived(npc.id)


func _check(condition: bool, message: String) -> void:
	if not condition:
		failures.append(message)
