extends SceneTree

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


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

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

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


func _check_manual_gate(failures: Array[String]) -> void:
	var state = _loaded_state(failures, "manual gate")
	if state == null:
		return
	var logs := []
	state.log_added.connect(func(message: String) -> void:
		logs.append(message)
	)
	state.fired_event_ids.clear()
	state.battle_events.clear()
	state.battle_events.append({
		"id": "dependent_report",
		"once": true,
		"when": {
			"type": "turn_start",
			"team": "player",
			"turn": 1,
			"after_event": "signal_ready"
		},
		"actions": [
			{"type": "log", "text": "Dependent event fired."}
		]
	})

	state._run_events("turn_start", "player", 1)
	if logs.has("Dependent event fired."):
		failures.append("after_event dependent fired before prerequisite")

	state.fired_event_ids["signal_ready"] = true
	state._run_events("turn_start", "player", 1)
	if not logs.has("Dependent event fired."):
		failures.append("after_event dependent did not fire after prerequisite")

	logs.clear()
	state._run_events("turn_start", "player", 1)
	if logs.has("Dependent event fired."):
		failures.append("after_event dependent repeated despite once flag")


func _check_same_pass_gate(failures: Array[String]) -> void:
	var state = _loaded_state(failures, "same pass gate")
	if state == null:
		return
	var logs := []
	state.log_added.connect(func(message: String) -> void:
		logs.append(message)
	)
	state.fired_event_ids.clear()
	state.battle_events.clear()
	state.battle_events.append({
		"id": "signal_ready",
		"once": true,
		"when": {"type": "turn_start", "team": "player", "turn": 1},
		"actions": [
			{"type": "log", "text": "Signal ready."}
		]
	})
	state.battle_events.append({
		"id": "dependent_report",
		"once": true,
		"when": {
			"type": "turn_start",
			"team": "player",
			"turn": 1,
			"after_event": "signal_ready"
		},
		"actions": [
			{"type": "log", "text": "Dependent event fired."}
		]
	})

	state._run_events("turn_start", "player", 1)
	if not logs.has("Signal ready."):
		failures.append("same-pass prerequisite did not fire")
	if not logs.has("Dependent event fired."):
		failures.append("same-pass dependent did not fire after prerequisite")


func _loaded_state(failures: Array[String], label: String):
	var state = BattleStateScript.new()
	if not state.load_battle("res://data/scenarios/001_yellow_turbans.json"):
		failures.append("%s could not load smoke scenario" % label)
		return null
	return state
