class_name AdtWaterSceneFinalizer
extends RefCounted

## Builds and attaches one ADT water subtree on the renderer main thread. The
## supplied tile root owns the returned subtree; this service retains no state.

const ADT_BUILDER_SCRIPT := preload("res://addons/mpq_extractor/loaders/adt_builder.gd")


## Builds water from parsed ADT data and attaches it once to [param tile_root].
## [param tile_origin_godot_units] is the existing Godot-world tile origin used
## by [ADTBuilder]. When [param editor_owner] is non-null and is an ancestor,
## ownership is assigned recursively for persisted Editor previews. Returns the
## attached borrowed root, or null for empty/invalid input or dry ADT data.
## This method mutates the SceneTree and must run on the main thread.
func attach_water_scene(
		water_data: Dictionary,
		tile_origin_godot_units: Vector3,
		tile_root: Node,
		editor_owner: Node = null) -> Node3D:
	if water_data.is_empty() or tile_root == null or not is_instance_valid(tile_root):
		return null

	var water_root: Node3D = ADT_BUILDER_SCRIPT.build_tile_water_scene(
		water_data,
		tile_origin_godot_units
	)
	if water_root == null:
		return null

	tile_root.add_child(water_root)
	if editor_owner != null and is_instance_valid(editor_owner):
		_assign_owner_recursive(water_root, editor_owner)
	return water_root


func _assign_owner_recursive(generated_node: Node, editor_owner: Node) -> void:
	generated_node.owner = editor_owner
	for child in generated_node.get_children():
		_assign_owner_recursive(child, editor_owner)
