extends Node

## NEO-74: prototype HTTP client for [code]POST /game/players/{id}/craft[/code] (NEO-70).

signal craft_result_received(recipe_id: String, result: Dictionary)
signal craft_request_failed(recipe_id: String, reason: String)

const SCHEMA_VERSION := 1

@export var base_url: String = "http://127.0.0.1:5253"
@export var dev_player_id: String = "dev-local-1"
@export var injected_http: Node = null

var _http: Node
var _busy: bool = false
var _current_recipe_id: String = ""


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 is_busy() -> bool:
	return _busy


## Returns [code]true[/code] when the HTTP POST was queued.
func request_craft(recipe_id: String, quantity: int = 1) -> bool:
	if _busy:
		return false
	var rid := recipe_id.strip_edges()
	if rid.is_empty():
		return false
	_current_recipe_id = rid
	_busy = true
	var payload: Dictionary = {
		"schemaVersion": SCHEMA_VERSION,
		"recipeId": rid,
		"quantity": quantity,
	}
	var url := "%s/game/players/%s/craft" % [_base_root(), _player_path_segment()]
	var headers := PackedStringArray(["Content-Type: application/json"])
	var err: Error = _http.request(url, headers, HTTPClient.METHOD_POST, JSON.stringify(payload))
	if err != OK:
		_busy = false
		_current_recipe_id = ""
		push_warning("CraftClient: POST failed to start (%s)" % err)
		return false
	return true


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


func _player_path_segment() -> String:
	return dev_player_id.strip_edges()


static func parse_craft_response_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
	if not root.has("success"):
		return null
	return root


func _on_request_completed(
	result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray
) -> void:
	var recipe_echo: String = _current_recipe_id
	_current_recipe_id = ""
	_busy = false
	if result != HTTPRequest.RESULT_SUCCESS:
		var reason := "HTTP failed (result=%s)" % result
		push_warning("CraftClient: %s" % reason)
		craft_request_failed.emit(recipe_echo, reason)
		return
	if response_code < 200 or response_code >= 300:
		var reason_code := "HTTP %s" % response_code
		push_warning("CraftClient: %s" % reason_code)
		craft_request_failed.emit(recipe_echo, reason_code)
		return
	var text := body.get_string_from_utf8()
	var parsed: Variant = parse_craft_response_json(text)
	if parsed == null:
		var reason_json := "non-JSON body or schemaVersion mismatch"
		push_warning("CraftClient: %s" % reason_json)
		craft_request_failed.emit(recipe_echo, reason_json)
		return
	var data: Dictionary = parsed as Dictionary
	var success: bool = bool(data.get("success", false))
	if not success:
		var reason_variant: Variant = data.get("reasonCode", "")
		var reason_str: String = reason_variant as String if reason_variant is String else ""
		push_warning("craft_denied reasonCode=%s" % reason_str)
	craft_result_received.emit(recipe_echo, data.duplicate(true))
