extends Node

## NEO-72: fetches [code]GET /game/world/item-definitions[/code] (NEO-53).
## Caches id → display metadata for inventory HUD labels.

signal definitions_ready(definitions_by_id: Dictionary)

const SCHEMA_VERSION := 1

@export var base_url: String = "http://127.0.0.1:5253"
@export var injected_http: Node = null

var _http: Node
var _busy: bool = false
var _definitions_by_id: Dictionary = {}


func _ready() -> void:
	if injected_http != null:
		_http = injected_http
	else:
		_http = HTTPRequest.new()
		add_child(_http)
		if _http is HTTPRequest:
			(_http as HTTPRequest).timeout = 30.0
	@warning_ignore("unsafe_method_access")
	_http.request_completed.connect(_on_request_completed)


func request_sync_from_server() -> void:
	if _busy:
		return
	_busy = true
	var url := "%s/game/world/item-definitions" % _base_root()
	var err: Error = _http.request(url)
	if err != OK:
		push_warning("ItemDefinitionsClient: GET failed to start (%s)" % err)
		_busy = false


func display_name_for(item_id: String) -> String:
	var row: Variant = _definitions_by_id.get(item_id, null)
	if row is Dictionary:
		var dn: Variant = (row as Dictionary).get("displayName", "")
		if dn is String and not (dn as String).is_empty():
			return dn as String
	return item_id


func definitions_map() -> Dictionary:
	return _definitions_by_id.duplicate(true)


static func build_definitions_map(root: Dictionary) -> Dictionary:
	var out: Dictionary = {}
	var raw_items: Variant = root.get("items", null)
	if raw_items == null or not raw_items is Array:
		return out
	for item in raw_items as Array:
		if not item is Dictionary:
			continue
		var row: Dictionary = item
		var id: Variant = row.get("id", null)
		if id == null or not id is String or (id as String).is_empty():
			continue
		out[id as String] = {
			"displayName": str(row.get("displayName", "")),
			"inventorySlotKind": str(row.get("inventorySlotKind", "")),
		}
	return out


func _base_root() -> String:
	return base_url.strip_edges().rstrip("/")


func _on_request_completed(
	result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray
) -> void:
	_busy = false
	if result != HTTPRequest.RESULT_SUCCESS:
		push_warning("ItemDefinitionsClient: HTTP failed (result=%s)" % result)
		return
	if response_code < 200 or response_code >= 300:
		push_warning("ItemDefinitionsClient: HTTP %s" % response_code)
		return
	var text := body.get_string_from_utf8()
	var parsed: Variant = JSON.parse_string(text)
	if not parsed is Dictionary:
		push_warning("ItemDefinitionsClient: non-JSON body")
		return
	var root: Dictionary = parsed
	if int(root.get("schemaVersion", -1)) != SCHEMA_VERSION:
		push_warning("ItemDefinitionsClient: schemaVersion mismatch")
		return
	_definitions_by_id = build_definitions_map(root)
	definitions_ready.emit(_definitions_by_id.duplicate(true))
