extends Node

## NEO-74: fetches [code]GET /game/world/recipe-definitions[/code] (NEO-68).
## Caches ordered recipe rows for craft UI.

signal recipes_ready(recipes: Array)
signal recipes_sync_failed(reason: String)

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 _recipes: Array = []


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/recipe-definitions" % _base_root()
	var err: Error = _http.request(url)
	if err != OK:
		var reason := "GET failed to start (%s)" % err
		push_warning("RecipeDefinitionsClient: %s" % reason)
		_busy = false
		recipes_sync_failed.emit(reason)


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


static func parse_recipes_json(text: String) -> Variant:
	var parsed: Variant = JSON.parse_string(text)
	if not parsed is Dictionary:
		return null
	var root: Dictionary = parsed
	if int(root.get("schemaVersion", -1)) != SCHEMA_VERSION:
		return null
	var recipes: Variant = root.get("recipes", null)
	if recipes == null or not recipes is Array:
		return null
	return recipes as Array


func _on_request_completed(
	result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray
) -> void:
	_busy = false
	if result != HTTPRequest.RESULT_SUCCESS:
		var reason := "HTTP failed (result=%s)" % result
		push_warning("RecipeDefinitionsClient: %s" % reason)
		recipes_sync_failed.emit(reason)
		return
	if response_code < 200 or response_code >= 300:
		var reason_code := "HTTP %s" % response_code
		push_warning("RecipeDefinitionsClient: %s" % reason_code)
		recipes_sync_failed.emit(reason_code)
		return
	var text := body.get_string_from_utf8()
	var recipes: Variant = parse_recipes_json(text)
	if recipes == null:
		var reason_json := "non-JSON body or schemaVersion mismatch"
		push_warning("RecipeDefinitionsClient: %s" % reason_json)
		recipes_sync_failed.emit(reason_json)
		return
	_recipes = (recipes as Array).duplicate(true)
	recipes_ready.emit(_recipes.duplicate(true))
