extends Node

## NS-18 / NEO-25: POST InteractionRequest; prints server allow/deny to Output (prototype).
## [kbd]E[/kbd] → [code]prototype_terminal[/code]; [kbd]R[/kbd] →
## [code]prototype_resource_node_alpha[/code] (stable contract ids — must match server registry).
## Key handling is delegated from
## [code]main.gd[/code] [method Node._unhandled_key_input] (see [method post_interact_terminal] /
## [method post_interact_resource]) so the embedded Game dock still receives E/R reliably.

const ID_TERMINAL := "prototype_terminal"
const ID_RESOURCE_NODE := "prototype_resource_node_alpha"

@export var base_url: String = "http://127.0.0.1:5253"
@export var dev_player_id: String = "dev-local-1"
## GdUnit: inject a mock transport (same pattern as [code]TargetSelectionClient[/code] test double).
@export var injected_http: Node = null

var _http: Node
var _busy: bool = false
## While an HTTP POST is in flight, the latest [code]interactableId[/code] from a new press
## overwrites this slot (last wins); [method _try_flush_pending] runs the next POST after
## [signal HTTPRequest.request_completed].
var _pending_interactable_id: String = ""
var _current_interactable_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 post_interact_terminal() -> void:
	_post_interact(ID_TERMINAL)


func post_interact_resource() -> void:
	_post_interact(ID_RESOURCE_NODE)


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


func _post_interact(interactable_id: String) -> void:
	if _busy:
		_pending_interactable_id = interactable_id
		return
	_start_post(interactable_id)


func _start_post(interactable_id: String) -> void:
	_current_interactable_id = interactable_id
	_busy = true
	var url := "%s/game/players/%s/interact" % [_base_root(), dev_player_id.strip_edges()]
	var payload := {"schemaVersion": 1, "interactableId": interactable_id}
	var body := JSON.stringify(payload)
	var headers := PackedStringArray(["Content-Type: application/json"])
	var err: Error = _http.request(url, headers, HTTPClient.METHOD_POST, body)
	if err != OK:
		push_warning("InteractionRequestClient: POST failed to start (%s)" % err)
		_busy = false
		_try_flush_pending()


func _try_flush_pending() -> void:
	var next: String = _pending_interactable_id
	_pending_interactable_id = ""
	if not next.is_empty() and not _busy:
		_start_post(next)


func _on_request_completed(
	_result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray
) -> void:
	_busy = false
	var text := body.get_string_from_utf8()
	var id_echo: String = _current_interactable_id
	if response_code == 200:
		var parsed: Variant = JSON.parse_string(text)
		if parsed is Dictionary:
			var d: Dictionary = parsed
			var allowed: bool = bool(d.get("allowed", false))
			var reason: Variant = d.get("reasonCode", null)
			if allowed:
				print("Interaction [%s]: allowed=true (reasonCode omitted on success)" % id_echo)
			else:
				print("Interaction [%s]: allowed=false reasonCode=%s" % [id_echo, str(reason)])
			_try_flush_pending()
			return
	print("Interaction [%s]: HTTP %s body=%s" % [id_echo, response_code, text])
	_try_flush_pending()
