extends Node

## NEO-31: prototype HTTP client for `POST /game/players/{id}/ability-cast`.
## NEO-28: emits [signal cast_result_received] when the response body is JSON
## [AbilityCastResponse] v1.
## NEO-30: [code]ability_cast_denied[/code] dev hook ([code]push_warning[/code] below). Deny
## [code]reasonCode[/code] is authoritative in [code]AbilityCastApi.cs[/code] (comment hook sites).
signal cast_result_received(accepted: bool, reason_code: String)

@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


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)


## [param target_id] server [code]lockedTargetId[/code] string, or [code]null[/code] if none.
## Returns [code]true[/code] when the HTTP POST was **queued**
## ([method HTTPRequest.request] returned [code]OK[/code]);
## [code]false[/code] if already [member _busy], request failed to start, or client invalid —
## use for [code]ability_cast_requested[/code] dev / future telemetry so hooks match actual submit
## attempts.
func request_cast(slot_index: int, ability_id: String, target_id: Variant) -> bool:
	if _busy:
		return false
	var tid: Variant = null
	if target_id is String:
		var s: String = target_id as String
		if not s.is_empty():
			tid = s
	var payload: Dictionary = {
		"schemaVersion": 1,
		"slotIndex": slot_index,
		"abilityId": ability_id,
		"targetId": tid,
	}
	var url := "%s/game/players/%s/ability-cast" % [_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:
		push_warning("AbilityCastClient: POST failed to start (%s)" % err)
		return false
	_busy = true
	return true


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


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


func _on_request_completed(
	result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray
) -> void:
	_busy = false
	if result != HTTPRequest.RESULT_SUCCESS:
		push_warning("AbilityCastClient: HTTP failed (result=%s)" % result)
		return
	if response_code < 200 or response_code >= 300:
		push_warning("AbilityCastClient: 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("AbilityCastClient: non-JSON body")
		return
	var data: Dictionary = parsed
	var accepted: bool = bool(data.get("accepted", false))
	var reason_variant: Variant = data.get("reasonCode", "")
	var reason: String = reason_variant as String if reason_variant is String else ""
	cast_result_received.emit(accepted, reason)
	if not accepted:
		# NEO-27 / NEO-31 / NEO-28: product hook name for future telemetry (TODO(E9.M1)).
		push_warning("ability_cast_denied reasonCode=%s" % reason)
