extends SceneTree

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


func _init() -> void:
	var failures: Array[String] = []
	_check_wuchao_depot_pickup(failures)

	if failures.is_empty():
		print("event item pickups smoke ok")
		quit(0)
		return

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


func _check_wuchao_depot_pickup(failures: Array[String]) -> void:
	var state = BattleStateScript.new()
	if not state.load_battle("res://data/scenarios/013_wuchao_raid.json"):
		failures.append("could not load Wuchao raid")
		return

	var logs: Array[String] = []
	var feedback: Array[String] = []
	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("%s|%s|%s" % [unit_id, text, kind])
	)

	var cao_cao: Dictionary = state.get_unit("cao_cao_ch13")
	if cao_cao.is_empty():
		failures.append("missing Cao Cao deployment in Wuchao raid")
		return

	var before_inventory := state.get_inventory_snapshot()
	cao_cao["pos"] = Vector2i(14, 4)
	state._run_events("unit_reaches_tile", "player", 1, cao_cao)

	var after_inventory := state.get_inventory_snapshot()
	if int(after_inventory.get("bean", 0)) != int(before_inventory.get("bean", 0)) + 2:
		failures.append("Wuchao depot should grant Bean x2: before %s after %s" % [str(before_inventory), str(after_inventory)])
	if int(after_inventory.get("wine", 0)) != int(before_inventory.get("wine", 0)) + 1:
		failures.append("Wuchao depot should grant Wine x1: before %s after %s" % [str(before_inventory), str(after_inventory)])
	if not logs.has("Usable Wuchao stores are seized before the granaries burn."):
		failures.append("Wuchao depot pickup log missing")
	if not logs.has("Received Bean x2."):
		failures.append("Bean pickup receipt log missing")
	if not logs.has("Received Wine."):
		failures.append("Wine pickup receipt log missing")
	if not feedback.has("cao_cao_ch13|+Bean|item"):
		failures.append("Bean pickup feedback missing")
	if not feedback.has("cao_cao_ch13|+Wine|item"):
		failures.append("Wine pickup feedback missing")
	if not state.fired_event_ids.has("wuchao_depot_burned"):
		failures.append("Wuchao depot event should be marked fired")

	logs.clear()
	feedback.clear()
	state._run_events("unit_reaches_tile", "player", 1, cao_cao)
	var repeat_inventory := state.get_inventory_snapshot()
	if int(repeat_inventory.get("bean", 0)) != int(after_inventory.get("bean", 0)):
		failures.append("Wuchao depot Bean pickup repeated despite once flag")
	if int(repeat_inventory.get("wine", 0)) != int(after_inventory.get("wine", 0)):
		failures.append("Wuchao depot Wine pickup repeated despite once flag")
	if not logs.is_empty() or not feedback.is_empty():
		failures.append("Wuchao depot pickup should not repeat logs or feedback")
