extends SceneTree
## Startup profiler (town fps / startup work 2026-10-02): which resources make loading main.tscn slow.
##   godot --path game -s res://scripts/tools/load_prof.gd [-- --root=res://scripts/main.gd]
## Walks the static preload("...") graph from the root script, loads it leaves-first and times every load
## (so each time is roughly the resource's OWN parse/compile cost), then prints every load (slowest first) and the total.

var _seen := {}
var _order: Array = []


func _initialize() -> void:
	var root := "res://scripts/main.gd"
	for a in OS.get_cmdline_user_args():
		if a.begins_with("--root="):
			root = a.substr(7)
	_walk(root)
	var times: Array = []
	var t_all := Time.get_ticks_usec()
	for p in _order:
		var t0 := Time.get_ticks_usec()
		var r = load(p)
		times.append([(Time.get_ticks_usec() - t0) / 1000.0, p, r != null])
	var total := (Time.get_ticks_usec() - t_all) / 1000.0
	times.sort_custom(func(a, b): return a[0] > b[0])
	var by_kind := {}
	for t in times:
		var k: String = (t[1] as String).get_extension()
		by_kind[k] = float(by_kind.get(k, 0.0)) + float(t[0])
	print("LOADPROF %d resources, total %.0f ms, by type %s" % [_order.size(), total, str(by_kind)])
	for i in times.size():
		print("LOADPROF %7.1f ms  %s%s" % [times[i][0], times[i][1], "" if times[i][2] else "  (FAILED)"])
	quit(0)


func _walk(path: String) -> void:
	if _seen.has(path):
		return
	_seen[path] = true
	if path.ends_with(".gd") or path.ends_with(".tscn") or path.ends_with(".gdshader") or path.ends_with(".gdshaderinc"):
		var f := FileAccess.open(path, FileAccess.READ)
		if f:
			var s := f.get_as_text()
			var re := RegEx.create_from_string("preload\\(\"(res://[^\"]+)\"\\)|path=\"(res://[^\"]+)\"|#include \"(res://[^\"]+)\"")
			for m in re.search_all(s):
				var dep := m.get_string(1)
				if dep == "":
					dep = m.get_string(2)
				if dep == "":
					dep = m.get_string(3)
				if dep != "" and FileAccess.file_exists(dep):
					_walk(dep)
	_order.append(path)
