extends SceneTree

func _initialize() -> void:
	var args := OS.get_cmdline_user_args()
	var map_name := _get_arg_value(args, "--map", "Azeroth")
	var extracted_dir := _normalize_res_path(_get_arg_value(args, "--extracted", "res://data/extracted"))
	var output_path := _normalize_output_path(_get_arg_value(args, "--output", "res://data/cache/m2_glb/%s_m2_list.txt" % map_name))

	if not ClassDB.class_exists("ADTLoader"):
		push_error("ADTLoader not found. Rebuild GDExtension first.")
		quit(1)
		return

	var loader = ClassDB.instantiate("ADTLoader")
	if loader == null:
		push_error("Failed to instantiate ADTLoader.")
		quit(1)
		return

	var map_dir := extracted_dir.path_join("World/Maps/%s" % map_name)
	var dir := DirAccess.open(map_dir)
	if dir == null:
		push_error("Cannot open map directory: %s" % map_dir)
		quit(1)
		return

	var unique_models := {}
	var scanned_tiles := 0

	for file_name in dir.get_files():
		if not file_name.ends_with(".adt"):
			continue

		var stem := file_name.trim_suffix(".adt")
		var parts := stem.split("_")
		if parts.size() != 3 or parts[0] != map_name:
			continue

		var source_abs_path := ProjectSettings.globalize_path(map_dir.path_join(file_name))
		var data: Dictionary = loader.call("load_adt", source_abs_path)
		if data.is_empty():
			continue

		var names: PackedStringArray = data.get("m2_names", PackedStringArray())
		for rel_path in names:
			var normalized := str(rel_path).replace("\\", "/")
			if not normalized.is_empty():
				unique_models[normalized.to_lower()] = normalized

		scanned_tiles += 1
		if scanned_tiles % 50 == 0:
			print("Scanned %d tiles..." % scanned_tiles)

	var models: PackedStringArray = PackedStringArray(unique_models.values())
	models.sort()

	var output_abs_path := ProjectSettings.globalize_path(output_path)
	DirAccess.make_dir_recursive_absolute(output_abs_path.get_base_dir())

	var file := FileAccess.open(output_path, FileAccess.WRITE)
	if file == null:
		push_error("Failed to open output file: %s" % output_path)
		quit(2)
		return

	for rel_path in models:
		file.store_line(rel_path)
	file.close()

	print("Collected %d unique M2 models from %d tiles -> %s" % [
		models.size(),
		scanned_tiles,
		output_path
	])
	quit(0)


func _get_arg_value(args: PackedStringArray, name: String, default_value: String) -> String:
	var index := args.find(name)
	if index >= 0 and index + 1 < args.size():
		return args[index + 1]
	return default_value


func _normalize_res_path(path: String) -> String:
	if path.begins_with("res://"):
		return path
	return "res://%s" % path.trim_prefix("./").trim_prefix("/")


func _normalize_output_path(path: String) -> String:
	if path.begins_with("res://") or path.begins_with("user://"):
		return path
	return "res://%s" % path.trim_prefix("./").trim_prefix("/")
