extends SceneTree

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


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

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

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


func _check_condition_cells(failures: Array[String]) -> void:
	var state = _loaded_state(failures, "condition cells")
	if state == null:
		return
	state.battle_conditions["victory"] = {
		"type": "unit_reaches_tile",
		"team": "player",
		"unit_ids": ["cao_cao"],
		"cells": [[2, 3], [2, 4]]
	}
	var objective_cells: Array[Vector2i] = state.get_objective_cells()
	if not objective_cells.has(Vector2i(2, 3)) or not objective_cells.has(Vector2i(2, 4)):
		failures.append("objective cells missing multi-cell destination: %s" % str(objective_cells))
	var progress: String = state.get_objective_progress_text(false)
	if not progress.contains("(3, 4), (3, 5): not reached"):
		failures.append("multi-cell progress text mismatch before reach: %s" % progress)
	var cao_cao: Dictionary = state.get_unit("cao_cao")
	cao_cao["pos"] = Vector2i(2, 4)
	progress = state.get_objective_progress_text(false)
	if not progress.contains("(3, 4), (3, 5): reached"):
		failures.append("multi-cell progress text mismatch after reach: %s" % progress)
	if not state._is_condition_met(state.battle_conditions["victory"]):
		failures.append("multi-cell unit_reaches_tile condition should be met")


func _check_event_cells(failures: Array[String]) -> void:
	var state = _loaded_state(failures, "event cells")
	if state == null:
		return
	var logs: Array[String] = []
	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": "multi_cell_cache",
		"once": true,
		"when": {"type": "unit_reaches_tile", "team": "player", "cells": [[3, 2], [3, 3]]},
		"actions": [
			{"type": "log", "text": "Multi-cell trigger fired."}
		]
	})
	var cao_cao: Dictionary = state.get_unit("cao_cao")
	cao_cao["pos"] = Vector2i(3, 3)
	state._run_events("unit_reaches_tile", "player", 1, cao_cao)
	if not logs.has("Multi-cell trigger fired."):
		failures.append("multi-cell event did not fire from second cell")


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
