@tool
extends EditorScript
## Regenerates all documentation for custom scripts
## Workaround for https://github.com/godotengine/godot/issues/72406

const ROOT_DIR := "res://"
const SCRIPT_EXTENSION := ".gd"
const PATH_LENGTH_LIMIT := 128

const PATH_BLACKLIST := [
	"res://utilities/regenerate_docs",  # This script MUST blacklist itself!
	"res://venv",
	"res://data_build",
	"res://data_sandbox",
]


func regen_docs(script_path: String) -> void:
	print("Regenerating docs for ", script_path)
	ResourceSaver.save(load(script_path))


func walk_directory(path: String) -> void:
	if len(path) > PATH_LENGTH_LIMIT:
		push_warning("Might be in a loop, skipping path ", path)
		return
	if path in PATH_BLACKLIST:
		push_warning("Skipping blacklisted path ", path)
		return

	var dir := DirAccess.open(path)
	if dir:
		dir.include_hidden = false
		dir.include_navigational = false
		dir.list_dir_begin()
		var file := dir.get_next()
		while file:
			var file_path := path.path_join(file)
			if dir.current_is_dir():
				walk_directory(file_path)
			elif file.ends_with(SCRIPT_EXTENSION):
				regen_docs(file_path)
			file = dir.get_next()


func _run() -> void:
	print("Regenerating custom script docs...")

	walk_directory(ROOT_DIR)

	print("Done!")
