extends RefCounted
## CC skill slot beside AUTO + the Samurai katanas (Boss 2026-10-21): selftest --only=ccslot (also in the full run).
##  - the slot exists, picks the class CC skill by itself, takes a dropped CC skill only (kept in the AUTO settings =
##    saved per character), right-click = auto again, the key "cc_skill" (C) is bound and casts it
##  - press: casts at the nearest monster without a target, the cooldown runs (120 s) and the slot shows it
##  - place: inside the screen, clear of AUTO / its gear / Attack / ULT / ASURA / hotbar / touch buttons / the combo
##    counter, PC pad mode and touch mode
##  - hook_spear / forgehand_hammer are katanas now (ids kept): Samurai wears them, no other class does, old saves load,
##    the hero holds the procedural katana
## --ccshots=<dir> (windowed run): PNGs of the PC HUD, the touch HUD and the Samurai holding both blades.

const SelfTest = preload("res://scripts/selftest.gd")
const CcSlot = preload("res://scripts/ui/cc_slot.gd")
const CC = preload("res://scripts/server/cc.gd")
const JobSlots = preload("res://scripts/server/job_slots.gd")
const AutoPlay = preload("res://scripts/auto_play.gd")
const CharacterState = preload("res://scripts/server/character_state.gd")


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


static func _shots() -> String:
	for a in OS.get_cmdline_user_args():
		if str(a).begins_with("--ccshots="):
			return str(a).substr(10)
	return ""


static func _arg(key: String, def: String) -> String:
	for a in OS.get_cmdline_user_args():
		if str(a).begins_with(key + "="):
			return str(a).substr(key.length() + 1)
	return def


static func _now() -> float:
	return Time.get_ticks_msec() / 1000.0


static func _as_class(pe, job: String, lv: int = 60) -> void:
	var ch = pe.ch
	ch.job = job
	ch.base_lv = lv
	ch.job_slots = []
	JobSlots.sync(ch)
	ch.skills = {}
	var sid := CC.skill_of(job)
	if sid != "" and lv >= 20:
		ch.skills[sid] = 1
	ch.wheel = {}
	ch.skill_cd = {}
	ch.buffs.clear()
	ch.hp = ch.max_hp()
	pe.s2 = {}
	PlayerState.changed.emit()


static func run(main: Node) -> void:
	print("SELFTEST ccslot")
	var old_flag = GameData.config.get("combat_v2", false)
	GameData.config["combat_v2"] = true
	var hud = main.hud
	var pe = main.me()
	var ch = pe.ch
	var saved: Dictionary = ch.to_dict()
	var pos0: Vector3 = pe.global_position
	var slot = hud.get_meta("cc_slot", null) if hud.has_meta("cc_slot") else null
	check(slot != null and slot.btn != null, "the HUD has the CC slot")
	if slot == null:
		return
	SelfTest.clear_mobs(main)
	for k in hud.windows:
		hud.windows[k].visible = false
	if hud.get("name_panel") != null:
		hud.name_panel.visible = false
	# ---- key binding
	check(Settings.default_binding("cc_skill")[0] == KEY_C and Settings.canon("cc_skill") == KEY_NONE, "key action cc_skill, default C")
	check(Settings.action_of(KEY_C, "cc_skill") == "", "C is not used by another action")
	# ---- which skill
	_as_class(pe, "hunt")
	PlayerState.auto_cfg["cc_slot"] = ""
	await SelfTest.frames(main, 3)
	check(CcSlot.skill_id() == "hu_cc_trap" and CcSlot.is_auto(), "auto pick = the class CC skill (Hunt: %s)" % CcSlot.skill_id())
	var picks := {}
	for j in JobSlots.launch_classes():
		var s := CC.skill_of(str(j))
		if s != "":
			picks[j] = s
	check(picks.size() == 5, "every launch class has a CC skill for the slot (%d)" % picks.size())
	_as_class(pe, "samurai")
	await SelfTest.frames(main, 2)
	check(CcSlot.skill_id() == "", "a class without a CC skill: empty slot")
	_as_class(pe, "musician", 15)
	await SelfTest.frames(main, 2)
	check(CcSlot.skill_id() == "mu_cc_bell" and PlayerState.skill_lv("mu_cc_bell") == 0 and slot.press() == "locked",
		"before Lv 20: the skill shows locked, pressing says so")
	# ---- drag & drop + saved per character
	_as_class(pe, "hunt")
	await SelfTest.frames(main, 2)
	var cc_pay := {"type": "hotbar_entry", "entry": "skill:hu_cc_trap", "from_slot": -1}
	check(slot._can_drop(Vector2.ZERO, cc_pay), "a CC skill can be dropped on the slot")
	check(not slot._can_drop(Vector2.ZERO, {"type": "hotbar_entry", "entry": "skill:hu_spiral_shot", "from_slot": -1})
		and not slot._can_drop(Vector2.ZERO, {"type": "hotbar_entry", "entry": "item:red_tonic", "from_slot": -1}),
		"a normal skill / an item cannot")
	slot._drop(Vector2.ZERO, cc_pay)
	check(str(PlayerState.auto_cfg.get("cc_slot", "")) == "hu_cc_trap" and not CcSlot.is_auto(), "drop: kept in the AUTO settings (cc_slot)")
	var c2 := CharacterState.new()
	c2.from_dict(ch.to_dict())
	check(str(c2.auto_cfg.get("cc_slot", "")) == "hu_cc_trap", "... saved with the character (survives save / load)")
	PlayerState.set_auto_cfg(PlayerState.auto_cfg.duplicate(true))
	check(str(PlayerState.auto_cfg.get("cc_slot", "")) == "hu_cc_trap", "... and through set_auto_cfg (what the server keeps)")
	# a class switch: the dropped skill is not this class's -> auto pick of the new class
	_as_class(pe, "magic_control")
	await SelfTest.frames(main, 2)
	check(CcSlot.skill_id() == "mc_cc_meteor" and CcSlot.is_auto(), "another class: its own CC skill (auto)")
	_as_class(pe, "hunt")
	var rc := InputEventMouseButton.new()
	rc.button_index = MOUSE_BUTTON_RIGHT
	rc.pressed = true
	slot._input_btn(rc)
	check(str(PlayerState.auto_cfg.get("cc_slot", "x")) == "" and CcSlot.is_auto(), "right-click: back to auto")
	# ---- AUTO still casts the CC skill by itself (setting auto_cc unchanged)
	PlayerState.auto_cfg["auto_cc"] = true
	check("hu_cc_trap" in AutoPlay.auto_skills(), "AUTO uses the CC skill (auto_cc on, no press needed)")
	# ---- press: nearest monster, cooldown on the slot
	var mid := ""
	for id in GameData.monsters:
		var md: Dictionary = GameData.monsters[id]
		if not md.get("boss", false) and not md.get("miniboss", false) and int(md.get("lv", 1)) >= 30 and int(md.get("lv", 1)) <= 60:
			mid = str(id)
			break
	var m = pe.map.spawn_mob(mid, pe.global_position + Vector3(5, 0, 0), 0.05, false)
	m.global_position = pe.global_position + Vector3(5, 0, 0)
	m.home = m.global_position
	m.think_t = 999.0
	m.max_hp = 50000000
	m.hp = m.max_hp
	pe.attack_target = null
	SelfTest.ready_to_act(pe)
	await SelfTest.frames(main, 6)
	var r: String = slot.press()
	await SelfTest.frames(main, 70)
	var cd: Vector2 = load("res://scripts/ui/skill_pad.gd").cd_of("hu_cc_trap")
	check(r == "target" and cd.x > 100.0, "press with no target: cast at the nearest monster, cooldown %.0f s on the slot (%s)" % [cd.x, r])
	check(m.buffs.has("root") or m.buffs.has("cc_slow") or m.buffs.has("silence"), "... the monster got the CC")
	# ---- the key casts it too (cooldown reset first)
	ch.skill_cd = {}
	SelfTest.ready_to_act(pe)
	await SelfTest.frames(main, 2)
	hud._on_key_action("cc_skill")
	await SelfTest.frames(main, 70)
	check(load("res://scripts/ui/skill_pad.gd").cd_of("hu_cc_trap").x > 100.0, "key C (action cc_skill) casts it")
	SelfTest.clear_mobs(main)
	# ---- place: PC pad mode + touch mode
	await _place_checks(main, hud, slot, false)
	var old_touch = Settings.val("touch_controls")
	Settings.set_value("touch_controls", "on")
	await SelfTest.frames(main, 20)
	await _place_checks(main, hud, slot, true)
	if _shots() != "":
		await _shot(main, "hud_touch")
	Settings.set_value("touch_controls", old_touch)
	await SelfTest.frames(main, 20)
	if _shots() != "":
		# a CC cooldown running on the slot for the picture
		ch.skill_cd = {"hu_cc_trap": _now() + 87.0}
		await _shot(main, "hud_pc")
		ch.skill_cd = {}
		await _shot(main, "hud_pc_ready")
	# ---- monster data (QA200 B2): Rustwing Drake's attack in its level band, fast-delay mini-bosses floored
	await _monster_checks(main, pe)
	# ---- katanas (hook_spear / forgehand_hammer)
	_katana_checks()
	await _katana_view(main, pe)
	# restore the tester
	ch.from_dict(saved)
	ch.skill_cd = {}
	pe.s2 = {}
	pe.attack_target = null
	pe.global_position = pos0
	PlayerState.changed.emit()
	GameData.config["combat_v2"] = old_flag
	await SelfTest.frames(main, 3)


static func _place_checks(main: Node, hud, slot, touch: bool) -> void:
	await SelfTest.frames(main, 2)
	var mode := "touch" if touch else "PC"
	var vs: Vector2 = hud.get_viewport().get_visible_rect().size
	var r: Rect2 = slot.btn.get_global_rect()
	check(slot.visible and slot.btn.is_visible_in_tree() and r.size.x >= 40.0, "%s: the slot shows (%s at %s)" % [mode, str(r), str(vs)])
	check(Rect2(Vector2.ZERO, vs).encloses(r), "%s: inside the screen %s" % [mode, str(vs)])
	var bad: Array = []
	var near_auto := false
	for b in hud.ui_root.find_children("*", "BaseButton", true, false):
		if b == slot.btn or slot.btn.is_ancestor_of(b) or not (b as Control).is_visible_in_tree():
			continue
		var br: Rect2 = (b as Control).get_global_rect()
		if br.size.x <= 1.0 or br.size.y <= 1.0 or br.size.x > vs.x * 0.5:
			continue
		if br.grow(-1.0).intersects(r.grow(-1.0)):
			bad.append("%s %s" % [b.name, str(br)])
	# the ASURA button (may be hidden at low level: its place must stay clear anyway)
	var au = hud.get_meta("asura_ui", null) if hud.has_meta("asura_ui") else null
	if au != null and au.get("btn") != null and not touch:
		var ar: Rect2 = au.btn.get_global_rect()
		if ar.size.x > 1.0 and ar.grow(-1.0).intersects(r.grow(-1.0)):
			bad.append("Asura %s" % str(ar))
	var co = main.get("combo")
	if co != null and co.has_method("screen_rect"):
		var cr: Rect2 = co.screen_rect(vs, touch)
		if cr.intersects(r):
			bad.append("combo %s" % str(cr))
	check(bad.is_empty(), "%s: clear of every other button / the combo counter %s" % [mode, str(bad)])
	var ar2: Rect2 = hud.auto_btn.get_global_rect()
	near_auto = r.get_center().distance_to(ar2.get_center()) < (r.size.x + ar2.size.x) * 1.4
	check(near_auto, "%s: right beside AUTO (%.0f px apart)" % [mode, r.get_center().distance_to(ar2.get_center())])


static func _monster_checks(main: Node, pe) -> void:
	var CombatV2 = load("res://scripts/server/combat_v2.gd")
	var rw: Dictionary = GameData.monsters.get("rustwing_drake", {})
	var hi := 0
	for id in GameData.monsters:
		var md: Dictionary = GameData.monsters[id]
		var lv := int(md.get("lv", 0))
		if id != "rustwing_drake" and lv >= 68 and lv <= 72 and not md.get("boss", false) and not md.get("miniboss", false):
			hi = maxi(hi, int((md.get("atk", [0, 0]) as Array)[-1]))
	var ra: Array = rw.get("atk", [0, 0])
	check(int(ra[-1]) <= hi and float(rw.get("delay", 0.0)) >= 1.0, "Rustwing Drake ATK %s within the Lv 68-72 band (max %d), delay %.2f" % [str(ra), hi, float(rw.get("delay", 0.0))])
	check(float(GameData.monsters.get("gale_wyrm", {}).get("delay", 0.0)) >= 1.0, "Gale Wyrm delay %.2f (B2 fix kept)" % float(GameData.monsters.get("gale_wyrm", {}).get("delay", 0.0)))
	# BALANCE 2026-10-26 (QA200 P3, sim99 probe: DC / MC / Hunt / Musician died 8-16x per 80 s on these zones): the three
	# zone monsters stay inside their level band - HP / ATK <= 1.25x the band's highest aggressive field monster, chase
	# speed <= 5 m/s (a hero on foot can still walk away), swing >= 1.4 s for the Rustwing pack
	for e in [["gale_wyrm", 74, 82], ["rustwing_drake", 66, 74], ["ember_grizzly", 64, 72]]:
		var me: Dictionary = GameData.monsters[e[0]]
		var bh := 0
		var ba := 0
		for id in GameData.monsters:
			var md: Dictionary = GameData.monsters[id]
			if id in ["gale_wyrm", "rustwing_drake", "ember_grizzly"] or md.has("realm") or bool(md.get("boss", false)) or bool(md.get("miniboss", false)) or not bool(md.get("aggressive", false)):
				continue
			if int(md.get("lv", 0)) >= int(e[1]) and int(md.get("lv", 0)) <= int(e[2]):
				bh = maxi(bh, int(md.get("hp", 0)))
				ba = maxi(ba, int((md.get("atk", [0, 0]) as Array)[-1]))
		check(float(me["hp"]) <= 1.25 * bh and float((me["atk"] as Array)[-1]) <= 1.25 * ba and float(me["speed"]) <= 5.0,
			"%s HP %d / ATK %d within the Lv %d-%d aggressive band (max HP %d / ATK %d), speed %.2f" % [e[0], int(me["hp"]), int((me["atk"] as Array)[-1]), int(e[1]), int(e[2]), bh, ba, float(me["speed"])])
	check(float(GameData.monsters["rustwing_drake"]["delay"]) >= 1.4, "Rustwing Drake swing %.2f s (pack of 10 aggressive)" % float(GameData.monsters["rustwing_drake"]["delay"]))
	# mini-bosses: combat_v2.json mini_boss.min_delay floors the swing - the old 0.076 and the fixed 0.76 hit alike
	for mid in ["fallen_paladin", "tidemother"]:
		var md: Dictionary = GameData.monsters[mid]
		var lo: Dictionary = md.duplicate(true)
		lo["delay"] = 0.076
		check(bool(md.get("miniboss", false)) and float(md.get("delay", 0.0)) >= 0.5 and is_equal_approx(CombatV2.mob_delay(md), CombatV2.mob_delay(lo)),
			"%s delay %.3f: real swing %.2f s = the same as with 0.076 (%.2f s)" % [mid, float(md.get("delay", 0.0)), CombatV2.mob_delay(md), CombatV2.mob_delay(lo)])
		var a: Array = await _duel(main, pe, mid, 0.076)
		var b: Array = await _duel(main, pe, mid, float(md.get("delay", 0.0)))
		check(int(a[0]) > 0 and absi(int(a[0]) - int(b[0])) <= 1 and is_equal_approx(float(a[1]), float(b[1])),
			"%s in a fight: %d swings / 4 s at delay 0.076, %d at %.3f (swing gap %.2f / %.2f s)" % [mid, int(a[0]), int(b[0]), float(md.get("delay", 0.0)), float(a[1]), float(b[1])])


## Monster `mid` (attack delay `delay`) next to the hero for 4 s: [swings, the swing gap the server used].
static func _duel(main: Node, pe, mid: String, delay: float) -> Array:
	SelfTest.clear_mobs(main)
	var ch = pe.ch
	var m = pe.map.spawn_mob(mid, pe.global_position + Vector3(1.2, 0, 0), 0.05, false)
	m.global_position = pe.global_position + Vector3(1.2, 0, 0)
	m.home = m.global_position
	m.data = m.data.duplicate(true)
	m.data["delay"] = delay
	m.data.erase("heavy")
	var got := [0, 0.0]
	ch.hp = 1 << 30
	var cb := func(e: Dictionary) -> void:
		if str(e.get("t", "")) == "attack" and int(e.get("id", 0)) == m.id:
			got[0] = int(got[0]) + 1
			got[1] = float(e.get("delay", 0.0))
	main.server.event.connect(cb)
	m.aggro(pe)
	var t0 := _now()
	while _now() - t0 < 4.0:
		# the hero must not fall (a Lv 140 mini-boss one-shots a test hero): HP topped up far over the max every frame
		ch.hp = 1 << 30
		await SelfTest.frames(main, 1)
	main.server.event.disconnect(cb)
	SelfTest.clear_mobs(main)
	ch.hp = ch.max_hp()
	return got


static func _katana_checks() -> void:
	for id in ["hook_spear", "forgehand_hammer"]:
		var it: Dictionary = GameData.item(id)
		check(str(it.get("wtype", "")) == "katana" and str(it.get("form", "")) == "katana", "%s is a katana now (wtype %s)" % [id, str(it.get("wtype", ""))])
		check(str(it.get("name_th", "")).contains("ดาบ") or str(it.get("name_th", "")).contains("คาตานะ"), "%s Thai name: %s" % [id, str(it.get("name_th", ""))])
		var who: Array = []
		for j in JobSlots.all_classes():
			var c := CharacterState.new()
			c.new_character("KtQa")
			c.job = str(j)
			c.job_slots = []
			JobSlots.sync(c)
			c.base_lv = 200
			if c.can_equip(id) == "":
				who.append(str(j))
		check(who == ["samurai"], "%s: only Samurai wears it %s" % [id, str(who)])
		# an old bag / equipped piece still loads (same id)
		var c1 := CharacterState.new()
		c1.new_character("KtOld")
		c1.job = "samurai"
		c1.job_slots = []
		JobSlots.sync(c1)
		c1.base_lv = 60
		c1.add_item(id, 2)
		var eq_ok: bool = c1.equip(id)
		var c2 := CharacterState.new()
		c2.from_dict(c1.to_dict())
		check(eq_ok and str(c2.equipment.get("weapon", {}).get("id", "")) == id and c2.count(id) >= 1, "%s: an old save (equipped + in the bag) loads" % id)


static func _katana_view(main: Node, pe) -> void:
	var ps = PlayerState
	_as_class(pe, "samurai")
	for id in ["forgehand_hammer", "hook_spear", "iron_katana"]:
		if ps.count(id) <= 0:
			ps.add_item(id, 1)
		ps.equip(id)
		ps.changed.emit()
		await SelfTest.frames(main, 8)
		var pl = main.player
		var wm = pl.get("weapon_mesh")
		var blade = wm.find_child("Blade", true, false) if wm != null else null
		check(str(ps.ch.equipment.get("weapon", {}).get("id", "")) == id and blade != null, "the Samurai holds %s as a katana (blade mesh %s)" % [id, str(blade != null)])
		if _shots() != "":
			var rig = main.get("rig")
			if rig != null:
				for h in main.hud.windows:
					main.hud.windows[h].visible = false
				rig.yaw = float(_arg("--ccyaw", "2.4"))
				rig.pitch = -0.18
				rig.dist = 4.6
				rig._apply()
			await _shot(main, "katana_" + id)


static func _shot(main: Node, tag: String) -> void:
	await SelfTest.frames(main, 30)
	await RenderingServer.frame_post_draw
	var img := main.get_viewport().get_texture().get_image()
	var p := _shots().path_join("cc_%s.png" % tag)
	img.save_png(p)
	print("CCSHOT ", p, " ", img.get_size())
