extends SceneTree

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


func _init() -> void:
	var failures: Array[String] = []
	_check_required_only_roster(failures)
	_check_optional_roster(failures)
	_check_roster_button_guard(failures)

	if failures.is_empty():
		print("roster choices smoke ok")
		quit(0)
		return

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


func _check_required_only_roster(failures: Array[String]) -> void:
	var state = _loaded_state(failures, "required-only roster", "res://data/scenarios/001_yellow_turbans.json")
	if state == null:
		return
	if not state.has_deployment_roster():
		failures.append("001 should keep roster rules for required deployments")
	if state.has_deployment_roster_choices():
		failures.append("001 should not expose roster choices when every player unit is required")
	if state.try_set_unit_deployed("cao_cao", false):
		failures.append("001 should not allow Cao Cao to be moved to reserve")
	if state.try_set_unit_deployed("xiahou_dun", false):
		failures.append("001 should not allow Xiahou Dun to be moved to reserve")


func _check_optional_roster(failures: Array[String]) -> void:
	var state = _loaded_state(failures, "optional roster", "res://data/scenarios/007_xian_emperor_escort.json")
	if state == null:
		return
	if not state.has_deployment_roster_choices():
		failures.append("007 should expose roster choices for optional deployed officers")


func _check_roster_button_guard(failures: Array[String]) -> void:
	var scene = BattleSceneScript.new()
	scene._create_hud()
	scene.state.load_battle("res://data/scenarios/001_yellow_turbans.json")
	scene.battle_started = false
	scene.briefing_panel.visible = true
	scene._on_roster_pressed()
	if scene.roster_menu.visible:
		failures.append("roster menu should not open when there are no roster choices")
	scene.free()


func _loaded_state(failures: Array[String], label: String, path: String):
	var state = BattleStateScript.new()
	if not state.load_battle(path):
		failures.append("%s could not load scenario: %s" % [label, path])
		return null
	return state
