extends RefCounted
## Status-window stat tooltips (Boss 2026-10-17, ui/stat_tip.gd): every derived number a base stat feeds, read from
## the REAL formulas (CharacterState / Combat / CombatV2 - nothing is re-implemented here), and the before -> after
## preview of +N points: the stat is raised on the character itself for the read, then put back (no signal, no
## save, same frame), so the preview is exactly what the server will compute after the raise.

const CombatV2 = preload("res://scripts/server/combat_v2.gd")

const STATS := ["str", "agi", "vit", "int", "dex", "luk"]
## = CharacterState.MAX_STAT (statguide_test.gd checks it)
const MAX_STAT := 200

## [key, label, format]: format "i" integer, "f1" one decimal, "pct" percent (x100, 1 decimal), "s2" seconds.
const ROWS := [
	["atk", "ATK", "i"],
	["status_atk", "Status ATK", "i"],
	["wmin", "Weapon min dmg", "i"],
	["matk_min", "MATK min", "i"],
	["matk_max", "MATK max", "i"],
	["hit", "HIT", "i"],
	["flee", "FLEE", "i"],
	["pdodge", "Perfect Dodge", "f1"],
	["crit", "CRIT", "f1"],
	["crit_dmg", "CRIT DMG", "i"],
	["super", "SUPER", "pct"],
	["aspd", "ASPD", "i"],
	["delay", "Attack delay", "s2"],
	["haste", "Haste", "f1"],
	["max_hp", "Max HP", "i"],
	["hp_regen", "HP Regen", "i"],
	["soft_def", "DEF (VIT)", "i"],
	["crit_res", "CRIT RES", "i"],
	["soft_mdef", "MDEF (INT)", "i"],
	["cast", "Cast time", "pct"],
	["heal", "Heal power", "i"],
	["br", "BR", "i"],
]


## Every derived value of the character now: {key: float}.
static func snapshot(c) -> Dictionary:
	var d := {}
	d["atk"] = float(c.atk_display())
	d["status_atk"] = float(c.status_atk())
	d["wmin"] = float(_weapon_min(c))
	d["matk_min"] = float(int(c.matk_min() * c.matk_rate()))
	d["matk_max"] = float(int(c.matk_max() * c.matk_rate()))
	d["hit"] = float(c.hit())
	d["flee"] = float(c.flee())
	d["pdodge"] = snappedf(c.perfect_dodge(), 0.1)
	d["crit"] = snappedf(c.crit_rate(), 0.1)
	d["crit_dmg"] = float(roundi(CombatV2.crit_dmg_rating(c)))
	d["super"] = snappedf(CombatV2.char_super_crit(c), 0.001)
	d["aspd"] = float(c.aspd())
	d["delay"] = snappedf(c.attack_delay(), 0.01)
	d["haste"] = snappedf(c.haste_pct(), 0.1)
	d["max_hp"] = float(c.max_hp())
	d["hp_regen"] = float(c.hp_regen())
	d["soft_def"] = float(c.soft_def())
	d["crit_res"] = float(roundi(CombatV2.crit_res_rating(c)))
	d["soft_mdef"] = float(c.soft_mdef())
	d["cast"] = snappedf(c.cast_rate(), 0.001)
	d["heal"] = float(_heal(c))
	d["br"] = float(CombatV2.battle_rating(c)) if CombatV2.enabled() else 0.0
	return d


## Combat.player_attack weapon part minimum: DEX x (80 + 20 x WLv) / 100, capped at the weapon ATK (bows: % of it).
static func _weapon_min(c) -> int:
	var wmax: int = c.weapon_atk()
	if wmax <= 0:
		return 0
	var wmin := mini(c.stat("dex") * (80 + 20 * c.weapon_lv()) / 100, wmax)
	if c.weapon_type() == "bow":
		wmin = wmin * wmax / 100
	return wmin


## Dawn Dance / Heal per cast at Lv 1 (Combat.heal_amount: (Base Lv + INT) / 8 x 12): only for the Musician.
static func _heal(c) -> int:
	if str(c.job) != "musician":
		return 0
	return c.heal_amount(1)


## Raise stat s by n on the character, take a snapshot, put it back. {} when the stat is unknown.
static func after(c, s: String, n: int = 1) -> Dictionary:
	if not (s in STATS):
		return {}
	var old := int(c.stats.get(s, 1))
	c.stats[s] = old + n
	var d := snapshot(c)
	c.stats[s] = old
	return d


## The rows that change from +n of stat s: [[key, label, before, after], ...] (in ROWS order).
static func changes(c, s: String, n: int = 1) -> Array:
	var a := snapshot(c)
	var b := after(c, s, n)
	var out: Array = []
	for r in ROWS:
		var k := str(r[0])
		if not is_equal_approx(float(a.get(k, 0.0)), float(b.get(k, 0.0))):
			out.append([k, str(r[1]), float(a[k]), float(b[k])])
	return out


## The smallest +n (2..10) that changes anything, 0 = none within 10 (only used when +1 changes nothing).
static func next_change(c, s: String) -> int:
	for n in range(2, 11):
		if int(c.stats.get(s, 1)) + n > MAX_STAT:
			return 0
		if not changes(c, s, n).is_empty():
			return n
	return 0


static func fmt(key: String, v: float) -> String:
	for r in ROWS:
		if str(r[0]) == key:
			match str(r[2]):
				"f1":
					return "%.1f" % v
				"pct":
					return "%.1f%%" % (v * 100.0)
				"s2":
					return "%.2fs" % v
	return str(int(round(v)))
