extends RefCounted
## Settings audit 2026-10-17 (docs/SETTINGS_AUDIT.md): selftest --only=settingsaudit (also in the full run).
## Every AUTO tab and every settings tab builds, the "Advanced" (ขั้นสูง) folds work, no weight option is left,
## the AUTO keys the window shows all have a default (so they survive save / load), old keys are dropped, presets.
## --bagshots=<dir> (windowed run): one screenshot per AUTO tab and per settings tab, Advanced opened.

const SelfTest = preload("res://scripts/selftest.gd")
const CharacterState = preload("res://scripts/server/character_state.gd")


static func check(ok: bool, what: String) -> void:
	SelfTest.check(ok, "settings audit: " + what)


static func _shot(main: Node, name: String) -> void:
	var dir := ""
	for a in OS.get_cmdline_user_args():
		if a.begins_with("--bagshots="):
			dir = a.substr(11)
	if dir == "" or DisplayServer.get_name() == "headless":
		return
	await SelfTest.frames(main, 8)
	var img := main.get_viewport().get_texture().get_image()
	img.save_png(dir.path_join("%s.png" % name))
	print("BAGSHOT ", name)


static func _open_adv(page: Node) -> int:
	var n := 0
	for t in page.find_children("AdvancedToggle", "Button", true, false):
		var body: Node = t.get_parent().find_child("AdvancedBody", false, false)
		if body and not body.visible:
			(t as Button).pressed.emit()
		n += 1
	return n


static func _texts(page: Node) -> String:
	var s := ""
	for l in page.find_children("*", "Label", true, false):
		s += str(l.text) + "\n" + str(l.tooltip_text) + "\n"
	for b in page.find_children("*", "BaseButton", true, false):
		s += str(b.tooltip_text) + "\n"
	return s


static func run(main: Node) -> void:
	var ps = PlayerState
	SelfTest.make_job(main, "swordman")
	ps.set_auto_cfg({})
	# ---- AUTO keys: every key the window shows has a default; old / dead keys are dropped
	var src := FileAccess.get_file_as_string("res://scripts/auto_ui.gd")
	var rx := RegEx.new()
	rx.compile("(?:switch_row|slider_row|option_row)\\(\\w+, \"(\\w+)\"")
	var missing: Array = []
	for m in rx.search_all(src):
		var k := m.get_string(1)
		if not CharacterState.AUTO_DEFAULTS.has(k) and not (k in missing):
			missing.append(k)
	check(missing.is_empty(), "every AUTO option has a default (persists through save / load) %s" % str(missing))
	var old := {"keep_distance": true, "loot_weight": 60.0, "stop_weight": 70.0, "stop_on_weight": true, "auto_awaken": true,
		"keep_fighting": false, "retaliate": false, "aspd_pot_on": true, "aspd_item": "concentration_potion", "auto_ult": false}
	ps.set_auto_cfg(old)
	var c: Dictionary = ps.auto_cfg
	check(not c.has("keep_distance") and not c.has("loot_weight") and not c.has("stop_weight") and not c.has("stop_on_weight") and not c.has("auto_awaken"),
		"old / dead keys are dropped on load")
	check(not bool(c["keep_fighting"]) and not bool(c["retaliate"]) and bool(c["aspd_pot_on"]) and str(c["aspd_item"]) == "concentration_potion" and not bool(c["auto_ult"]),
		"keep_fighting / retaliate / attack-speed potion / ULT switches survive save / load")
	var c2 := CharacterState.new()
	c2.from_dict({"auto": old})
	check(not bool(c2.auto_cfg["keep_fighting"]) and bool(c2.auto_cfg["aspd_pot_on"]), "... also through a character file")
	ps.set_auto_cfg({})
	check(bool(ps.auto_cfg["keep_fighting"]) and bool(ps.auto_cfg["retaliate"]) and bool(ps.auto_cfg["auto_ult"]) and not bool(ps.auto_cfg["aspd_pot_on"]),
		"defaults: never stop fighting, attackers first, ULT on, no attack-speed potion")
	ps.apply_auto_preset("safe")
	check(not bool(ps.auto_cfg["keep_fighting"]) and is_equal_approx(float(ps.auto_cfg["retreat_pct"]), 35.0), "preset Safe really retreats at 35% (keep_fighting off)")
	ps.apply_auto_preset("aggressive")
	check(bool(ps.auto_cfg["keep_fighting"]), "preset Aggressive never stops fighting")
	for p in CharacterState.AUTO_PRESETS:
		check(not (CharacterState.AUTO_PRESETS[p] as Dictionary).has("keep_distance"), "preset %s has no dead keys" % p)
	ps.set_auto_cfg({})
	# ---- AUTO window: every tab builds, Advanced folds, no weight text
	var hud = main.hud
	var aui = hud.auto_ui
	if not aui.panel.visible:
		aui.open()
	var adv_n := 0
	var weight_hits: Array = []
	for t in aui.TABS:
		aui.show_tab(str(t[0]))
		await SelfTest.frames(main, 2)
		adv_n += _open_adv(aui.page)
		await SelfTest.frames(main, 2)
		var txt := _texts(aui.page).to_lower()
		if txt.contains("weight") or txt.contains("น้ำหนัก"):
			weight_hits.append(str(t[0]))
		check(aui.page.get_child_count() > 0, "AUTO tab %s builds" % str(t[0]))
		await _shot(main, "auto_%s" % str(t[0]))
	check(adv_n >= 4, "AUTO: %d tabs fold their less-used options under Advanced" % adv_n)
	check(weight_hits.is_empty(), "AUTO: no weight text left %s" % str(weight_hits))
	aui.show_tab("combat")
	await SelfTest.frames(main, 2)
	var titles := ""
	for l in aui.page.find_children("*", "Label", true, false):
		titles += str(l.text) + "|"
	check(not titles.contains("Fighting style"), "AUTO combat: the empty Fighting style card is gone")
	aui.show_tab("safety")
	await SelfTest.frames(main, 2)
	var kf: CheckButton = aui.page.find_child("Opt_keep_fighting", true, false)
	var rs: HSlider = null
	for s in aui.page.find_children("*", "HSlider", true, false):
		rs = s
		break
	if kf and rs:
		kf.button_pressed = true
		await SelfTest.frames(main, 1)
		var grey: bool = not rs.editable
		kf.button_pressed = false
		await SelfTest.frames(main, 1)
		check(grey and rs.editable, "AUTO safety: the retreat rows are greyed while Never stop fighting is on")
		kf.button_pressed = true
	else:
		check(false, "AUTO safety: keep_fighting switch + retreat slider found")
	aui.panel.visible = false
	hud.windows["auto"].visible = false
	ps.set_auto_cfg({})
	# ---- game settings window: every tab, Advanced folds, F pickup note
	var st = main.get_node_or_null("/root/Settings")
	check(st != null, "Settings autoload")
	if st:
		st.open_menu("graphics")
		await SelfTest.frames(main, 3)
		var sui = st.ui
		var sadv := 0
		var f_note := false
		for t in sui.TABS:
			sui.show_tab(str(t[0]))
			await SelfTest.frames(main, 2)
			sadv += _open_adv(sui.page)
			await SelfTest.frames(main, 2)
			check(sui.page.get_child_count() > 0, "settings tab %s builds" % str(t[0]))
			if str(t[0]) == "controls":
				f_note = _texts(sui.page).contains("F = ") or _texts(sui.page).contains("F = เก็บ")
			await _shot(main, "settings_%s" % str(t[0]))
		check(sadv >= 3, "settings: graphics / lighting / camera fine-tuning folded under Advanced (%d)" % sadv)
		check(f_note, "settings controls: the F pickup key is listed")
		st.close_menu()
	# ---- Thai for the new texts
	var th = JSON.parse_string(FileAccess.get_file_as_string("res://data/i18n_th.json"))
	var miss: Array = []
	for k in ["Advanced", "Show", "Hide", "Show / hide the less-used options.", "Less-used options.",
			"Only with \"Never stop fighting\" off: with no HP potion left and HP under this, AUTO stops fighting and retreats.",
			"Camera follow speed, rotate / zoom speed, invert."]:
		if not (th is Dictionary) or str(th.get(k, "")) == "":
			miss.append(k)
	check(miss.is_empty(), "Thai for the audit texts %s" % str(miss))
