# Autoload operations module
# Handles: add_autoload, remove_autoload, list_autoloads
# Corresponds to: test_autoload.py
class_name AutoloadOps


## Add an autoload to the project
static func add_autoload(ctx: SceneTree, params: Dictionary) -> void:
	ctx.log_info("Adding autoload: " + params.name)

	# Normalize script path
	var script_path: String = params.script_path
	if not script_path.begins_with("res://"):
		script_path = "res://" + script_path

	if not FileAccess.file_exists(script_path):
		ctx.log_error("Script file does not exist: " + script_path)
		ctx.quit(1)

	# Check if autoload already exists
	if ProjectSettings.has_setting("autoload/" + params.name):
		ctx.log_error("Autoload already exists: " + params.name)
		ctx.quit(1)

	# Add autoload setting
	ProjectSettings.set_setting("autoload/" + params.name, "*" + script_path)

	# Save project settings
	var save_error: int = ProjectSettings.save()
	if save_error != OK:
		ctx.log_error("Failed to save project settings: " + str(save_error))
		ctx.quit(1)

	if ctx.debug_mode:
		print("[DEBUG] Autoload added to project.godot")

	print("Autoload '" + params.name + "' added successfully")


## Remove an autoload from the project
static func remove_autoload(ctx: SceneTree, params: Dictionary) -> void:
	ctx.log_info("Removing autoload: " + params.name)

	var setting_name: String = "autoload/" + params.name

	# Check if autoload exists
	if not ProjectSettings.has_setting(setting_name):
		ctx.log_error("Autoload does not exist: " + params.name)
		ctx.quit(1)

	# Remove autoload setting
	ProjectSettings.set_setting(setting_name, null)

	# Save project settings
	var save_error: int = ProjectSettings.save()
	if save_error != OK:
		ctx.log_error("Failed to save project settings: " + str(save_error))
		ctx.quit(1)

	if ctx.debug_mode:
		print("[DEBUG] Autoload removed from project.godot")

	print("Autoload '" + params.name + "' removed successfully")


## List all autoloads in the project
static func list_autoloads(ctx: SceneTree, params: Dictionary) -> void:
	var autoloads: Array = []

	# Iterate through all project settings
	for setting in ProjectSettings.get_property_list():
		var setting_name: String = setting.name
		if setting_name.begins_with("autoload/"):
			var autoload_name: String = setting_name.replace("autoload/", "")
			var autoload_path: String = ProjectSettings.get_setting(setting_name)

			# Remove the * prefix if present (indicates singleton)
			var is_singleton: bool = autoload_path.begins_with("*")
			if is_singleton:
				autoload_path = autoload_path.substr(1)

			autoloads.append({
				"name": autoload_name,
				"path": autoload_path,
				"singleton": is_singleton
			})

	# Output as JSON
	print(JSON.stringify({"autoloads": autoloads}, "\t"))
