@tool
extends Node

## Reads and modifies ProjectSettings and input map.


func register(server: Node) -> void:
	server.register_handler("project_settings", _project_settings)
	server.register_handler("get_input_map", _get_input_map)
	server.register_handler("save_scene", _save_scene)


func _project_settings(args: Dictionary) -> Dictionary:
	var action: String = args.get("action", "get")
	var key: String = args.get("key", "")

	if action == "list":
		# Return commonly useful settings
		var settings := [
			"application/config/name",
			"application/config/description",
			"application/run/main_scene",
			"display/window/size/viewport_width",
			"display/window/size/viewport_height",
			"display/window/stretch/mode",
			"display/window/stretch/aspect",
			"rendering/renderer/rendering_method",
			"physics/2d/default_gravity",
			"physics/3d/default_gravity",
		]
		var lines: PackedStringArray = []
		for s in settings:
			if ProjectSettings.has_setting(s):
				lines.append("%s = %s" % [s, str(ProjectSettings.get_setting(s))])
		return {"ok": true, "type": "text", "result": "\n".join(lines)}

	if key.is_empty():
		return {"ok": false, "error": "Missing 'key' argument"}

	if action == "get":
		if not ProjectSettings.has_setting(key):
			return {"ok": false, "error": "Setting not found: %s" % key}
		var value = ProjectSettings.get_setting(key)
		return {"ok": true, "type": "text", "result": "%s = %s" % [key, str(value)]}

	if action == "set":
		var value = args.get("value")
		if value == null:
			return {"ok": false, "error": "Missing 'value' argument for set"}
		ProjectSettings.set_setting(key, value)
		ProjectSettings.save()
		return {"ok": true, "type": "text", "result": "Set %s = %s" % [key, str(value)]}

	return {"ok": false, "error": "Unknown action: %s (use 'get', 'set', or 'list')" % action}


func _get_input_map(_args: Dictionary) -> Dictionary:
	var actions := InputMap.get_actions()
	var lines: PackedStringArray = []

	for action in actions:
		# Skip built-in UI actions
		if str(action).begins_with("ui_"):
			continue
		var events := InputMap.action_get_events(action)
		var event_strs: PackedStringArray = []
		for event in events:
			event_strs.append(event.as_text())
		if event_strs.size() > 0:
			lines.append("%s: %s" % [action, ", ".join(event_strs)])
		else:
			lines.append("%s: (no bindings)" % action)

	if lines.size() == 0:
		return {"ok": true, "type": "text", "result": "No custom input actions defined."}

	return {"ok": true, "type": "text", "result": "\n".join(lines)}


func _save_scene(_args: Dictionary) -> Dictionary:
	var root := EditorInterface.get_edited_scene_root()
	if root == null:
		return {"ok": false, "error": "No scene open"}

	var scene_path := root.scene_file_path
	if scene_path.is_empty():
		return {"ok": false, "error": "Scene has no file path — save it manually first"}

	EditorInterface.save_scene()
	return {"ok": true, "type": "text", "result": "Scene saved: %s" % scene_path}
