extends SceneTree

const BattleStateScript := preload("res://scripts/core/battle_state.gd")


func _init() -> void:
	var failures: Array[String] = []
	var state = BattleStateScript.new()
	if not state.load_battle("res://data/scenarios/001_yellow_turbans.json"):
		push_error("Could not load AI priority smoke scenario.")
		quit(1)
		return

	_check_priority_action(state, failures)
	_check_priority_changes_enemy_targeting(state, failures)

	if failures.is_empty():
		print("event ai priority smoke ok")
		quit(0)
		return

	for failure in failures:
		push_error(failure)
	quit(1)


func _check_priority_action(state, failures: Array[String]) -> void:
	var logs: Array[String] = []
	var feedback: Array[Dictionary] = []
	state.log_added.connect(func(message: String) -> void:
		logs.append(message)
	)
	state.combat_feedback_requested.connect(func(unit_id: String, text: String, kind: String) -> void:
		feedback.append({"unit_id": unit_id, "text": text, "kind": kind})
	)

	state._execute_event_action({
		"type": "set_ai_target_priority",
		"unit_id": "xiahou_dun",
		"priority": 9,
		"text": "Xiahou Dun draws the enemy's focus."
	})

	var target: Dictionary = state.get_unit("xiahou_dun")
	if int(target.get("ai_target_priority", 0)) != 9:
		failures.append("AI target priority did not update on event action")
	if not logs.has("Xiahou Dun draws the enemy's focus."):
		failures.append("AI priority event log missing")
	if not _feedback_has(feedback, "xiahou_dun", "TARGET", "priority"):
		failures.append("AI priority feedback missing")


func _check_priority_changes_enemy_targeting(state, failures: Array[String]) -> void:
	var enemy: Dictionary = state.get_unit("yellow_turban_1")
	var target: Dictionary = state._find_nearest_target(enemy, "player")
	if str(target.get("id", "")) != "xiahou_dun":
		failures.append("AI priority did not affect nearest target scoring: %s" % str(target.get("id", "")))


func _feedback_has(feedback: Array[Dictionary], expected_unit_id: String, expected_text: String, expected_kind: String) -> bool:
	for entry in feedback:
		if (
			str(entry.get("unit_id", "")) == expected_unit_id
			and str(entry.get("text", "")) == expected_text
			and str(entry.get("kind", "")) == expected_kind
		):
			return true
	return false
