@tool
extends EditorPlugin

const AUTOLOAD_NAME := "GolemCapture"

const HANDLERS := {
	"screenshot_handler": preload("handlers/screenshot_handler.gd"),
	"scene_handler": preload("handlers/scene_handler.gd"),
	"inspect_handler": preload("handlers/inspect_handler.gd"),
	"run_handler": preload("handlers/run_handler.gd"),
	"script_handler": preload("handlers/script_handler.gd"),
	"project_handler": preload("handlers/project_handler.gd"),
	"input_handler": preload("handlers/input_handler.gd"),
}

var _server: GolemServer


func _enter_tree() -> void:
	# Register game capture autoload
	if not ProjectSettings.has_setting("autoload/" + AUTOLOAD_NAME):
		var script_path := (get_script() as Script).resource_path.get_base_dir() + "/golem_capture.gd"
		add_autoload_singleton(AUTOLOAD_NAME, script_path)

	# Create TCP server
	_server = preload("golem_server.gd").new()
	_server.name = "GolemServer"
	add_child(_server)

	# Create and register all handlers
	for ref_name in HANDLERS:
		var handler: Node = HANDLERS[ref_name].new()
		handler.name = ref_name.to_pascal_case()
		_server.add_child(handler)
		_server.set(ref_name, handler)
		handler.register(_server)

	print("Golem MCP: Plugin loaded — TCP server on port %d" % GolemServer.PORT)


func _exit_tree() -> void:
	if _server:
		_server.stop()
		_server.queue_free()
		_server = null

	if ProjectSettings.has_setting("autoload/" + AUTOLOAD_NAME):
		remove_autoload_singleton(AUTOLOAD_NAME)

	print("Golem MCP: Plugin unloaded")
