extends Node

## NEO-85: prototype HTTP client for [code]GET /game/world/combat-targets[/code] (NEO-83).

signal targets_received(snapshot: Dictionary)
signal targets_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 _last_snapshot: 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/combat-targets" % _base_root()
	var err: Error = _http.request(url)
	if err != OK:
		var reason := "GET failed to start (%s)" % err
		push_warning("CombatTargetsClient: %s" % reason)
		_busy = false
		targets_sync_failed.emit(reason)


func target_row(target_id: String, snapshot: Dictionary = {}) -> Dictionary:
	var source: Dictionary = snapshot
	if source.is_empty():
		source = _last_snapshot
	var targets: Variant = source.get("targets", null)
	if targets == null or not targets is Array:
		return {}
	for row_variant in targets as Array:
		if not row_variant is Dictionary:
			continue
		var row: Dictionary = row_variant
		if str(row.get("targetId", "")) == target_id:
			return row
	return {}


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


static func parse_targets_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 targets: Variant = root.get("targets", null)
	if targets == null or not targets is Array:
		return null
	return root


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("CombatTargetsClient: %s" % reason)
		targets_sync_failed.emit(reason)
		return
	if response_code < 200 or response_code >= 300:
		var reason_code := "HTTP %s" % response_code
		push_warning("CombatTargetsClient: %s" % reason_code)
		targets_sync_failed.emit(reason_code)
		return
	var text := body.get_string_from_utf8()
	var snapshot: Variant = parse_targets_json(text)
	if snapshot == null:
		var reason_json := "non-JSON body or schemaVersion mismatch"
		push_warning("CombatTargetsClient: %s" % reason_json)
		targets_sync_failed.emit(reason_json)
		return
	_last_snapshot = snapshot as Dictionary
	targets_received.emit(_last_snapshot)
