extends Node

## Auto-discovers and registers all buff resources from res://docs/gyms/buffs/

const BUFF_DIRECTORY_PATH: String = "res://docs/gyms/buffs"

var _buff_by_id: Dictionary = {}
var _initialized: bool = false

func _ready() -> void:
	_initialize_buff_catalog()

func _initialize_buff_catalog() -> void:
	if _initialized:
		return
	
	_buff_by_id.clear()
	var dir: DirAccess = DirAccess.open(BUFF_DIRECTORY_PATH)
	if dir == null:
		push_warning("Unable to open buff directory: %s" % BUFF_DIRECTORY_PATH)
		_initialized = true
		return
	
	dir.list_dir_begin()
	var entry_name: String = dir.get_next()
	while not entry_name.is_empty():
		if not dir.current_is_dir() and entry_name.ends_with(".tres"):
			var path: String = "%s/%s" % [BUFF_DIRECTORY_PATH, entry_name]
			var buff: GeneratorBuffData = load(path) as GeneratorBuffData
			if buff != null:
				_buff_by_id[buff.id] = buff
				GameState.register_buff(buff)
		entry_name = dir.get_next()
	dir.list_dir_end()
	
	_initialized = true
	print("BuffDatabase initialized with %d buffs" % _buff_by_id.size())

func get_all_buffs() -> Array[GeneratorBuffData]:
	var result: Array[GeneratorBuffData] = []
	for buff in _buff_by_id.values():
		if buff is GeneratorBuffData:
			result.append(buff)
	return result

func get_buff(buff_id: StringName) -> GeneratorBuffData:
	return _buff_by_id.get(buff_id, null)
