# Project settings operations module
# Handles: set_project_setting_op, get_project_setting_op, list_resources_op
# Corresponds to: test_project_settings.py, test_e2e_project_settings.py, test_scripting_resources.py
class_name ProjectOps


## Set a project setting in project.godot
static func set_project_setting_op(ctx: SceneTree, params: Dictionary) -> void:
	var setting_key: String = params.setting_key
	var setting_value: Variant = params.setting_value
	
	print("Setting project setting: " + setting_key + " = " + str(setting_value))
	
	if ctx.debug_mode:
		print("Setting key: " + setting_key)
		print("Setting value: " + str(setting_value))
		print("Setting value type: " + str(typeof(setting_value)))
	
	# Set the setting
	ProjectSettings.set_setting(setting_key, setting_value)
	
	if ctx.debug_mode:
		# Verify the setting was set
		var current_value: Variant = ProjectSettings.get_setting(setting_key)
		print("Current value after set: " + str(current_value))
	
	# Save the project settings
	var error: int = ProjectSettings.save()
	if ctx.debug_mode:
		print("Save result: " + str(error) + " (OK=" + str(OK) + ")")
	
	if error == OK:
		print("Project setting set successfully: " + setting_key + " = " + str(setting_value))
	else:
		printerr("Failed to save project settings: " + str(error))
		ctx.quit(1)


## Get a project setting from project.godot
static func get_project_setting_op(ctx: SceneTree, params: Dictionary) -> void:
	var setting_key: String = params.setting_key
	
	print("Getting project setting: " + setting_key)
	
	if ctx.debug_mode:
		print("Setting key: " + setting_key)
	
	# Get the setting value
	var value: Variant = ProjectSettings.get_setting(setting_key)
	
	if ctx.debug_mode:
		print("Setting value: " + str(value))
		print("Setting value type: " + str(typeof(value)))
	
	# Return the value as JSON
	var result: Dictionary = {
		"key": setting_key,
		"value": value,
		"type": typeof(value)
	}
	print(JSON.stringify(result))


## List resource files in the project
## @param ctx: SceneTree - The main script context
## @param params: Dictionary - Parameters from Python:
##   - directory: String - Optional subdirectory to search in
##   - extensions: Array - List of file extensions to include
##   - recursive: bool - Whether to search recursively (default: true)
static func list_resources_op(ctx: SceneTree, params: Dictionary) -> void:
	var directory: String = params.get("directory", "")
	var extensions: Array = params.get("extensions", [])
	var recursive: bool = params.get("recursive", true)
	
	if ctx.debug_mode:
		print("[DEBUG] Listing resources in directory: " + directory)
		print("[DEBUG] Extensions: " + str(extensions))
	
	# Normalize directory path
	var search_path: String = "res://"
	if not directory.is_empty():
		if directory.begins_with("res://"):
			search_path = directory
		else:
			search_path = "res://" + directory
	
	# Ensure path ends with /
	if not search_path.ends_with("/"):
		search_path += "/"
	
	# Find all resource files
	var resources: Dictionary = {
		"images": [],
		"audio": [],
		"models": [],
		"fonts": [],
		"resources": [],
		"other": [],
	}
	
	var all_files: Array = _find_resources_recursive(search_path, extensions, recursive, ctx.debug_mode)
	
	# Categorize files
	for file_path: String in all_files:
		var relative_path: String = file_path
		if relative_path.begins_with("res://"):
			relative_path = relative_path.substr(6)
		
		var ext: String = file_path.get_extension().to_lower()
		
		if ext in ["png", "jpg", "jpeg", "webp", "svg", "bmp"]:
			resources["images"].append(relative_path)
		elif ext in ["wav", "mp3", "ogg"]:
			resources["audio"].append(relative_path)
		elif ext in ["glb", "gltf", "obj", "fbx"]:
			resources["models"].append(relative_path)
		elif ext in ["ttf", "otf"]:
			resources["fonts"].append(relative_path)
		elif ext in ["tres", "res"]:
			resources["resources"].append(relative_path)
		else:
			resources["other"].append(relative_path)
	
	# Count total
	var total_count: int = 0
	for category: String in resources:
		total_count += resources[category].size()
	
	resources["total_count"] = total_count
	
	# Output as JSON
	var json_output: String = JSON.stringify(resources)
	print(json_output)


## Helper function to recursively find resource files
static func _find_resources_recursive(path: String, extensions: Array, recursive: bool, debug_mode: bool) -> Array:
	var files: Array = []
	var dir: DirAccess = DirAccess.open(path)
	
	if dir == null:
		if debug_mode:
			print("[DEBUG] Could not open directory: " + path)
		return files
	
	dir.list_dir_begin()
	var file_name: String = dir.get_next()
	
	while file_name != "":
		if file_name.begins_with("."):
			file_name = dir.get_next()
			continue
		
		var full_path: String = path + file_name
		
		if dir.current_is_dir():
			if recursive:
				files.append_array(_find_resources_recursive(full_path + "/", extensions, true, debug_mode))
		else:
			# Check if extension matches
			var ext: String = file_name.get_extension().to_lower()
			if extensions.is_empty() or ext in extensions:
				files.append(full_path)
				if debug_mode:
					print("[DEBUG] Found resource: " + full_path)
		
		file_name = dir.get_next()
	
	dir.list_dir_end()
	return files
