extends RefCounted
## Gear Runes P0 + P1 (server/gear_opts.gd, data/gear_options.json): selftest --only=gearopt (also part of the full run).
##  data sanity, grade / tier / line rolls (seeded), rules (max 2 same, 1 strong % per piece, low-level pieces <= 2 lines),
##  save / load + migration (old pieces = white, tampered lines cleaned), the character save and the net replica dict,
##  stats into equip_bonus / card_pct with the per-stat totals, server drops (grade on the ground, the spawn event "g",
##  pickup keeps the lines), parcel / trash keep the lines, plain-first selling, the POWER CAP (worst-case SS gear on
##  reference characters <= cap.share of BR / damage / EHP) and the tooltip.
##  --gearoptshots=<png path> (windowed run): one sheet with the tooltip of the same piece in the 5 grades.

const SelfTest = preload("res://scripts/selftest.gd")
const CharacterState = preload("res://scripts/server/character_state.gd")
const GearOpts = preload("res://scripts/server/gear_opts.gd")
const CombatV2 = preload("res://scripts/server/combat_v2.gd")
const Bag = preload("res://scripts/server/bag.gd")
const NetProto = preload("res://scripts/net/net_proto.gd")

const CAP_SLOTS := ["weapon", "armor", "head", "garment", "shoes", "accessory", "shield"]


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


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


static func run(main: Node) -> void:
	GearOpts.mode = 0
	_data_checks()
	_roll_checks()
	_save_checks()
	_char_save_checks()
	_stat_checks()
	await _server_checks(main)
	_cap_checks()
	await _ui_checks(main)
	GearOpts.mode = 0


# ---------------------------------------------------------------- data

static func _data_checks() -> void:
	var d := GearOpts.data()
	check(not d.is_empty(), "data/gear_options.json loads")
	var gs: Array = d.get("grades", [])
	var lines_ok := gs.size() == 5
	for i in gs.size():
		lines_ok = lines_ok and int(gs[i].get("lines", -1)) == i
	check(lines_ok, "5 grades white / green / blue / purple / gold with 0..4 lines")
	var dw: Dictionary = d.get("drop_weights", {})
	var sum_ok := true
	for k in ["normal", "mini", "boss"]:
		var s := 0.0
		for w in dw.get(k, []):
			s += float(w)
		sum_ok = sum_ok and absf(s - 100.0) < 0.01 and (dw.get(k, []) as Array).size() == 5
	check(sum_ok, "drop weights of normal / mini / boss sum to 100%")
	check(is_equal_approx(float(dw["normal"][0]), 60.0) and is_equal_approx(float(dw["normal"][4]), 0.2), "field monsters: 60% white .. 0.2% gold (spec 6.2)")
	check(float(dw["mini"][0]) == 0.0 and float(dw["mini"][1]) == 0.0 and float(dw["boss"][0]) == 0.0 and float(dw["boss"][1]) == 0.0, "mini-boss / MVP drops are at least blue")
	var tw := 0.0
	for t in d.get("tiers", []):
		tw += float(t.get("w", 0))
	check((d.get("tiers", []) as Array).size() == 5 and absf(tw - 100.0) < 0.01, "5 tiers C / B / A / S / SS, weights sum to 100")
	var pools_ok := true
	for slot in d.get("slot_pools", {}):
		for fam in d["slot_pools"][slot]:
			var sd: Dictionary = d.get("stats", {}).get(str(fam), {})
			pools_ok = pools_ok and not sd.is_empty() and (sd.get("max", []) as Array).size() == 5
	check(pools_ok, "every pool stat exists with a max for each of the 5 level bands")
	check(not (d.get("slot_pools", {}) as Dictionary).has("costume_weapon"), "costumes never carry runes")
	check(GearOpts.band(1) == 0 and GearOpts.band(29) == 0 and GearOpts.band(30) == 1 and GearOpts.band(119) == 3 and GearOpts.band(160) == 4, "level bands 1-29 / 30-59 / 60-89 / 90-119 / 120+")


# ---------------------------------------------------------------- rolls

## A high-level weapon / armour piece and a low-level one (req_lv < 20) from items.json.
static func _pick(slot: String, min_lv: int, max_lv: int) -> String:
	var best := ""
	for id in GameData.items:
		var it: Dictionary = GameData.items[id]
		if str(it.get("type", "")) != "equip" or str(it.get("slot", "")) != slot or str(id).begins_with("tester_"):
			continue
		var lv := GearOpts.item_lv(str(id))
		if lv >= min_lv and lv <= max_lv and (best == "" or lv > GearOpts.item_lv(best)):
			best = str(id)
	return best


static func _roll_checks() -> void:
	var hi := _pick("weapon", 90, 200)
	var lo := _pick("weapon", 1, 19)
	check(hi != "" and lo != "", "test pieces: %s (Lv %d) and %s (Lv %d)" % [hi, GearOpts.item_lv(hi), lo, GearOpts.item_lv(lo)])
	var rng := RandomNumberGenerator.new()
	rng.seed = 20261021
	var n := 20000
	var cnt := [0, 0, 0, 0, 0]
	for i in n:
		cnt[GearOpts.roll_grade(hi, "normal", rng)] += 1
	var exp_w := [60.0, 28.0, 10.0, 1.8, 0.2]
	var dist_ok := true
	var txt: Array = []
	for g in 5:
		var p := 100.0 * float(cnt[g]) / float(n)
		txt.append("%.1f" % p)
		dist_ok = dist_ok and absf(p - exp_w[g]) <= maxf(0.25, exp_w[g] * 0.08)
	check(dist_ok, "field drop grades over %d rolls ~ 60 / 28 / 10 / 1.8 / 0.2 %% (got %s)" % [n, " / ".join(txt)])
	var mini_ok := true
	var boss_gold := 0
	for i in 3000:
		mini_ok = mini_ok and GearOpts.roll_grade(hi, "mini", rng) >= 2
		if GearOpts.roll_grade(hi, "boss", rng) == 4:
			boss_gold += 1
	check(mini_ok, "mini-boss drops: never below blue")
	check(boss_gold > 150, "MVP drops: gold far more often (%d / 3000)" % boss_gold)
	# low-level pieces: grade capped at blue = at most 2 lines
	var lo_ok := true
	for i in 2000:
		var f := GearOpts.roll_fields(lo, "boss", rng)
		lo_ok = lo_ok and int(f.get("grade", 0)) <= 2 and (f.get("opts", []) as Array).size() <= 2
	check(lo_ok and GearOpts.max_grade(lo) == 2, "pieces below Lv 20: at most blue / 2 lines")
	check(GearOpts.roll_grade("red_tonic", "boss", rng) == 0 and GearOpts.roll_fields("red_tonic", "boss", rng).is_empty(), "non-equipment never gets a grade")
	# lines: count = grade, rules, values in range, tier ranges
	var rules_ok := true
	var vals_ok := true
	var tiers := [0, 0, 0, 0, 0]
	var armor := _pick("armor", 90, 200)
	for i in 4000:
		var id := hi if i % 2 == 0 else armor
		var g := 1 + i % 4
		var opts := GearOpts.roll_opts(id, g, rng)
		rules_ok = rules_ok and opts.size() == g
		var same := {}
		var strong := 0
		for o in opts:
			var s := str(o["stat"])
			same[s] = int(same.get(s, 0)) + 1
			rules_ok = rules_ok and int(same[s]) <= 2 and GearOpts.pool(id).has(GearOpts.family(s)) and GearOpts.valid_stat(s)
			if bool(GearOpts.stat_def(s).get("strong", false)):
				strong += 1
			var mx := GearOpts.stat_max(s, GearOpts.item_lv(id))
			vals_ok = vals_ok and int(o["val"]) >= 1 and int(o["val"]) <= mx
			tiers[int(o["tier"])] += 1
		rules_ok = rules_ok and strong <= 1
	check(rules_ok, "lines = grade count, from the slot's pool, max 2 of a stat, max 1 strong % stat per piece")
	check(vals_ok, "every value is 1 .. the band's max")
	var tsum := 0.0
	for t in tiers:
		tsum += float(t)
	check(absf(100.0 * tiers[0] / tsum - 45.0) < 2.5 and absf(100.0 * tiers[4] / tsum - 1.0) < 0.6, "tier weights ~45%% C .. 1%% SS (C %.1f%%, SS %.2f%%)" % [100.0 * tiers[0] / tsum, 100.0 * tiers[4] / tsum])
	var ss_ok := true
	for s in ["str", "batk", "aspd_rate", "add_race:brute"]:
		ss_ok = ss_ok and GearOpts.roll_val(s, 4, GearOpts.item_lv(hi), rng) == GearOpts.stat_max(s, GearOpts.item_lv(hi))
	check(ss_ok, "an SS line is the band's max value")
	check(GearOpts.stat_max("batk", 1) < GearOpts.stat_max("batk", 130), "values grow with the piece's level band (ATK %d -> %d)" % [GearOpts.stat_max("batk", 1), GearOpts.stat_max("batk", 130)])
	var o1 := {"stat": "str", "val": 3, "tier": 3}
	check(GearOpts.line_text(o1) == "STR +3 [S]", "line text 'STR +3 [S]' (%s)" % GearOpts.line_text(o1))
	check(GearOpts.line_value({"stat": "sub_ele:fire", "val": 2, "tier": 0}, true).contains("ไฟ"), "Thai line names (%s)" % GearOpts.line_value({"stat": "sub_ele:fire", "val": 2, "tier": 0}, true))


# ---------------------------------------------------------------- save / load (P0)

static func _graded(id: String, g: int, tier: int = 2) -> Dictionary:
	var rng := RandomNumberGenerator.new()
	rng.seed = 7 + g
	var opts: Array = []
	for i in GearOpts.grade_lines(g):
		opts.append(GearOpts.roll_line(id, opts, rng, tier))
	return GearOpts.apply(CharacterState.make_inst(id), {"grade": g, "opts": opts})


static func _same_opts(a: Dictionary, b: Dictionary) -> bool:
	if GearOpts.grade_of(a) != GearOpts.grade_of(b):
		return false
	var oa := GearOpts.opts_of(a)
	var ob := GearOpts.opts_of(b)
	if oa.size() != ob.size():
		return false
	for i in oa.size():
		if str(oa[i]["stat"]) != str(ob[i]["stat"]) or int(oa[i]["val"]) != int(ob[i]["val"]) or int(oa[i]["tier"]) != int(ob[i]["tier"]):
			return false
	return true


static func _save_checks() -> void:
	var id := _pick("weapon", 90, 200)
	var inst := _graded(id, 4)
	inst["pity"] = 12
	var sv := CharacterState.inst_save(inst)
	check(int(sv.get("grade", 0)) == 4 and (sv.get("opts", []) as Array).size() == 4 and int(sv.get("pity", 0)) == 12, "a gold piece saves grade / 4 lines / pity")
	var back := CharacterState._inst_from(JSON.parse_string(JSON.stringify(sv)))
	check(_same_opts(inst, back) and int(back.get("pity", 0)) == 12, "save -> JSON -> load keeps every line (ints, not floats)")
	var white := CharacterState.make_inst(id)
	var sw := CharacterState.inst_save(white)
	check(not sw.has("grade") and not sw.has("opts") and not sw.has("pity"), "a white piece saves exactly as before (no extra bytes)")
	# migration: an old save entry has no grade -> white, nothing lost
	var old := CharacterState._inst_from({"id": id, "refine": 7, "cards": [], "heat": 20.0})
	check(GearOpts.grade_of(old) == 0 and GearOpts.opts_of(old).is_empty() and int(old["refine"]) == 7 and float(old.get("heat", 0)) == 20.0, "old piece (no grade) loads as white, refine / heat kept")
	check(CharacterState._inst_from(id).get("id", "") == id and GearOpts.grade_of(CharacterState._inst_from(id)) == 0, "oldest save format (a bare id string) loads as white")
	# tampered / stale data is cleaned on load (the server never trusts a line it did not roll in this shape)
	var bad := {"id": id, "refine": 0, "cards": [], "grade": 2, "opts": [
		{"stat": "str", "val": 999, "tier": 9}, {"stat": "no_such_stat", "val": 5, "tier": 1},
		{"stat": "def", "val": 3, "tier": 1}, {"stat": "dex", "val": 1, "tier": 0}, {"stat": "luk", "val": 1, "tier": 0}]}
	var cl := CharacterState._inst_from(bad)
	var co := GearOpts.opts_of(cl)
	check(co.size() == 2 and str(co[0]["stat"]) == "str" and int(co[0]["val"]) == GearOpts.stat_max("str", GearOpts.item_lv(id)) and int(co[0]["tier"]) == 4, "load clamps values / tiers to the band")
	check(co.size() == 2 and str(co[1]["stat"]) == "dex", "load drops unknown stats and stats outside the slot's pool (DEF on a weapon), keeps <= grade lines")
	var lo := _pick("weapon", 1, 19)
	check(GearOpts.grade_of(CharacterState._inst_from({"id": lo, "refine": 0, "cards": [], "grade": 4, "opts": []})) == 2, "a low-level piece saved as gold loads capped at blue")
	check(not CharacterState.is_plain(inst) and CharacterState.is_plain(white), "a graded piece is never 'plain' (selling / turn-ins by id take white pieces first)")
	var pr := Bag.precious(PlayerState.ch, id, _graded(id, 2))
	check(pr != "", "blue+ pieces are precious in the trash dialog (%s)" % pr)


static func _char_save_checks() -> void:
	var c := CharacterState.new()
	c.new_character("RuneSave")
	var wid := _pick("weapon", 1, 19)
	var aid := _pick("armor", 1, 19)
	var w := _graded(wid, 2)
	var a := _graded(aid, 1)
	c.gear.append(w)
	c.equipment["armor"] = a
	var n0: int = c.gear.size()
	var d = JSON.parse_string(JSON.stringify(c.to_dict()))
	var c2 := CharacterState.new()
	c2.from_dict(d)
	var w2: Dictionary = {}
	for inst in c2.gear:
		if str(inst["id"]) == wid and GearOpts.grade_of(inst) == 2:
			w2 = inst
	check(c2.gear.size() == n0 and not w2.is_empty() and _same_opts(w, w2) and c2.equipment.has("armor") and _same_opts(a, c2.equipment["armor"]), "character save / load keeps bag + worn lines")
	# an old character (pieces without grade) loads with every piece, all white
	var od: Dictionary = (d as Dictionary).duplicate(true)
	for e in od["gear"]:
		(e as Dictionary).erase("grade")
		(e as Dictionary).erase("opts")
	for k in od["equipment"]:
		(od["equipment"][k] as Dictionary).erase("grade")
		(od["equipment"][k] as Dictionary).erase("opts")
	var c3 := CharacterState.new()
	c3.from_dict(od)
	var white := true
	for inst in c3.gear:
		white = white and GearOpts.grade_of(inst) == 0
	check(c3.gear.size() == n0 and c3.equipment.has("armor") and white and GearOpts.grade_of(c3.equipment["armor"]) == 0, "old character: loads, no piece lost, everything white")
	# net replica: the owner's character dict carries the lines (and nothing for white pieces)
	var nd: Dictionary = NetProto.char_dict(c)
	var has_opts := false
	var white_clean := true
	for e in nd["gear"]:
		if int(e.get("grade", 0)) > 0:
			has_opts = (e.get("opts", []) as Array).size() == GearOpts.grade_lines(int(e["grade"]))
		else:
			white_clean = white_clean and not e.has("opts") and not e.has("grade")
	check(has_opts and white_clean, "net replica dict: graded pieces carry grade + lines, white pieces add nothing")
	var rep := CharacterState.new()
	rep.from_dict(nd)
	var rw: Dictionary = {}
	for inst in rep.gear:
		if GearOpts.grade_of(inst) == 2:
			rw = inst
	check(not rw.is_empty() and _same_opts(w, rw), "the client replica shows the same lines")
	var line_bytes := JSON.stringify(CharacterState.inst_save(_graded(wid, 2))).length() - JSON.stringify(CharacterState.inst_save(CharacterState.make_inst(wid))).length()
	check(line_bytes > 0 and line_bytes < 150, "sync cost of a 2-line piece: +%d bytes" % line_bytes)


# ---------------------------------------------------------------- stats (P1)

static func _stat_checks() -> void:
	var c := CharacterState.new()
	c.new_character("RuneStats")
	c.base_lv = 99
	var wid := _pick("weapon", 90, 200)
	var hid := _pick("head", 60, 200)
	if hid == "":
		hid = _pick("head", 1, 200)
	c.equipment = {}
	var w := CharacterState.make_inst(wid)
	c.equipment["weapon"] = w
	var s0: int = c.stat("str")
	var b0: int = c.equip_bonus("batk")
	var r0: int = c.card_pct("add_race", "brute")
	GearOpts.apply(w, {"grade": 3, "opts": [{"stat": "str", "val": 1, "tier": 2}, {"stat": "batk", "val": 2, "tier": 2}, {"stat": "add_race:brute", "val": 3, "tier": 3}]})
	check(c.stat("str") == s0 + 1 and c.equip_bonus("batk") == b0 + 2, "worn lines add to stats / ATK (STR %d -> %d, ATK +%d)" % [s0, c.stat("str"), c.equip_bonus("batk") - b0])
	check(c.card_pct("add_race", "brute") == r0 + 3 and c.card_pct("add_race", "plant") == 0, "race % line feeds card_pct (only that race)")
	var mon := {"race": "brute", "element": "neutral", "size": "medium"}
	check(c.card_mult(mon) > 1.0, "the race line raises damage vs brutes (x%.2f)" % c.card_mult(mon))
	GearOpts.mode = 2
	check(c.stat("str") == s0 and c.card_pct("add_race", "brute") == r0, "measuring mode 'off' removes the layer")
	GearOpts.mode = 0
	# per-stat total over everything worn (character band 90-119)
	var h := CharacterState.make_inst(hid)
	c.equipment["head"] = h
	GearOpts.apply(h, {"grade": 3, "opts": [{"stat": "batk", "val": 3, "tier": 4}, {"stat": "batk", "val": 3, "tier": 4}, {"stat": "str", "val": 1, "tier": 4}]})
	var cap := GearOpts.stat_total("batk", 99)
	check(cap > 0 and c.equip_bonus("batk") == b0 + mini(8, cap) and c.stat("str") == s0 + mini(2, GearOpts.stat_total("str", 99)), "ATK from all worn lines capped at %d (worn sum %d), STR at %d" % [cap, GearOpts.worn_sum(c, "batk"), GearOpts.stat_total("str", 99)])
	# a bag piece gives nothing
	c.equipment.erase("head")
	c.gear.append(h)
	check(c.equip_bonus("batk") == b0 + 2 and c.stat("str") == s0 + 1, "lines on a piece in the bag give nothing")
	# refine and runes stay apart
	w["refine"] = 9
	check(c.stat("str") == s0 + 1 and int(GearOpts.opts_of(w)[1]["val"]) == 2, "refining does not touch the lines (and lines do not touch refine)")


# ---------------------------------------------------------------- server: drops, pickup, parcel, trash

static func _server_checks(main: Node) -> void:
	var ps = PlayerState
	SelfTest.make_job(main, "swordman")
	var pe = main.me()
	var c = ps.ch
	var map = pe.map
	var wid := _pick("weapon", 1, 200)
	# MVP drop: on the ground with its grade, the spawn event says only the grade
	var l = map.drop_item(wid, 1, pe.global_position + Vector3(1, 0, 0), "boss")
	check(int(l.inst.get("grade", 0)) >= 2, "an MVP drop lies on the ground already graded (%s)" % GearOpts.grade_name(int(l.inst.get("grade", 0))))
	var ev: Dictionary = map.spawn_event_of(l)
	check(int(ev.get("g", 0)) == int(l.inst["grade"]) and not ev.has("opts") and not ev.has("inst"), "loot spawn event: grade only ('g'), no lines (lean net)")
	var rolled: Dictionary = (l.inst as Dictionary).duplicate(true)
	var n0: int = c.gear.size()
	pe._pickup(l)
	var got: Dictionary = c.gear[-1] if c.gear.size() > n0 else {}
	check(not got.is_empty() and str(got["id"]) == wid and int(got.get("grade", 0)) == int(rolled["grade"]) and _same_opts(got, rolled), "pickup: the piece in the bag has exactly the lines rolled at the drop")
	# a stackable and a shop piece stay plain
	var l2 = map.drop_item("red_tonic", 3, pe.global_position, "boss")
	check(l2.inst.is_empty() and not map.spawn_event_of(l2).has("g"), "stackable drops have no grade")
	map.remove_loot(l2)
	var l3 = map.drop_item(wid, 1, pe.global_position)
	check(l3.inst.is_empty(), "drop_item without a source (tests / PK drops) stays white")
	map.remove_loot(l3)
	c.zeny = 1000000
	var nb: int = c.gear.size()
	c.buy(wid, 1)
	check(c.gear.size() == nb + 1 and GearOpts.grade_of(c.gear[-1]) == 0, "NPC shop pieces are always white")
	# a kill rolls through on_mob_died: force a field drop table on a dummy and count graded drops
	var hits := 0
	var tot := 0
	for i in 400:
		var f := GearOpts.roll_fields(wid, "normal")
		tot += 1
		if not f.is_empty():
			hits += 1
	check(hits > 80 and hits < 240, "field kill rolls: ~40%% of equipment drops get a grade (%d / %d)" % [hits, tot])
	# give(): treasure / steal path
	var gi := GearOpts.give(c, wid, "mini")
	check(not gi.is_empty() and GearOpts.grade_of(gi) >= 2 and c.gear.has(gi), "give() (treasure gold chest / steal): equipment gets rolled lines")
	var tn: int = c.count("red_tonic")
	check(GearOpts.give(c, "red_tonic", "boss").is_empty() and c.count("red_tonic") == tn + 1, "give() of a stackable adds it normally")
	# parcel keeps the lines
	var keep: Dictionary = _graded(wid, 3)
	var cap0 = c.bagx.get("x", 0)
	while c.slots_free() > 0:
		c.add_item("tester_blade" if GameData.item("tester_blade").size() > 0 else wid, 1)
	c.add_inst(keep)
	var par: Array = c.bag_state()["parcel"]
	check(not par.is_empty() and par[-1].has("inst") and int(par[-1]["inst"].get("grade", 0)) == 3, "full bag: a graded piece waits in the parcel with its lines")
	# free slots and claim
	var removed := 0
	for inst in c.gear.duplicate():
		if GearOpts.grade_of(inst) == 0 and removed < 3:
			c.gear.erase(inst)
			removed += 1
	c.claim_parcel()
	var claimed: Dictionary = {}
	for inst in c.gear:
		if _same_opts(inst, keep) and GearOpts.grade_of(inst) == 3:
			claimed = inst
	check(not claimed.is_empty(), "parcel -> bag: the lines come back intact")
	c.bagx["x"] = cap0
	# trash -> undo keeps the lines
	Bag._rate.clear()
	var r: Dictionary = main.send({"t": "bag", "op": "discard", "id": wid, "uid": c.uid_of(claimed), "n": 1, "sure": true})
	check(bool(r.get("ok", false)), "discard a graded piece (with the precious confirm)")
	var r2: Dictionary = main.send({"t": "bag", "op": "undo", "i": (c.bagx["trash"] as Array).size() - 1})
	var back: Dictionary = {}
	for inst in c.gear:
		if GearOpts.grade_of(inst) == 3 and _same_opts(inst, keep):
			back = inst
	check(bool(r2.get("ok", false)) and not back.is_empty(), "trash undo: the piece returns with the same lines")
	# selling by id takes white pieces first, the graded one stays
	var wcount := 0
	for inst in c.gear:
		if str(inst["id"]) == wid and GearOpts.grade_of(inst) == 0:
			wcount += 1
	if wcount > 0:
		c.sell(wid, 1)
		check(c.gear.has(back), "sell by id: a white piece goes first, the graded one stays")
	c.gear.clear()
	c.bagx = {}
	c.changed.emit()


# ---------------------------------------------------------------- power cap (spec 6.10)

## Best piece of a slot for `job` at `lv` (highest level, then attack / defence).
static func _best_item(job: String, slot: String, lv: int) -> String:
	var weapons: Array = GameData.jobs.get(job, {}).get("weapons", [])
	var best := ""
	var best_k := -1.0
	for id in GameData.items:
		var it: Dictionary = GameData.items[id]
		if str(it.get("type", "")) != "equip" or str(it.get("slot", "")) != slot or str(id).begins_with("tester_") or it.has("skin"):
			continue
		if GearOpts.item_lv(str(id)) > lv:
			continue
		if slot == "weapon" and not weapons.has(str(it.get("wtype", ""))):
			continue
		if it.has("jobs") and not (it["jobs"] as Array).has(job):
			continue
		var k := float(GearOpts.item_lv(str(id))) * 1000.0 + float(it.get("atk", 0)) + float(it.get("def", 0)) * 5.0 + float(it.get("matk_rate", 0)) * 3.0
		if k > best_k:
			best_k = k
			best = str(id)
	return best


## Reference character: `job` at Base Lv `lv`, stats spent for its role, the best gear it can wear (+7 weapon, +4 armour).
static func _ref_char(job: String, lv: int, off: int = 0) -> CharacterState:
	var c := CharacterState.new()
	c.new_character("RuneCap")
	c.job = job
	c.base_lv = lv
	c.job_lv = 50
	var main_s := clampi(int(lv * 0.9) + 5, 1, 120)
	var st := {"str": 1, "agi": 1, "vit": 1, "int": 1, "dex": 1, "luk": 1}
	match job:
		"hunt":
			st = {"dex": main_s, "agi": int(lv * 0.6), "str": int(lv * 0.3), "luk": int(lv * 0.2) + 1, "vit": int(lv * 0.3) + 1, "int": 1}
		"magic_control":
			st = {"int": main_s, "dex": int(lv * 0.6), "vit": int(lv * 0.4) + 1, "agi": 1, "str": 1, "luk": 1}
		_:
			st = {"str": main_s, "agi": int(lv * 0.5), "vit": int(lv * 0.5) + 1, "dex": int(lv * 0.4), "luk": int(lv * 0.15) + 1, "int": 1}
	for s in st:
		c.stats[s] = maxi(1, int(st[s]))
	c.gear.clear()
	c.equipment = {}
	for slot in CAP_SLOTS:
		var id := _best_item(job, slot, lv)
		if id == "":
			continue
		if slot == "shield" and c.equipment.has("weapon") and bool(GameData.item(str(c.equipment["weapon"]["id"])).get("two_handed", false)):
			continue
		c.equipment[slot] = CharacterState.make_inst(id, 7 if slot == "weapon" else 4)
	# the main stat's final value at (10 k + off): classic (STAT / 10)^2 steps make one point worth anything from
	# +1 to +2b+1 ATK, so the cap is measured as the average over 4 positions of that step
	var ms := "dex" if job == "hunt" else ("int" if job == "magic_control" else "str")
	c.stats[ms] = int(c.stats[ms]) + ((off - c.stat(ms) % 10) + 10) % 10
	c.hp = c.max_hp()
	return c


## A field monster near `lv` (its race / element / size and hit for the damage and EHP numbers).
static func _ref_mon(lv: int) -> Dictionary:
	var best: Dictionary = {}
	var bd := 9999
	for mid in GameData.monsters:
		var m: Dictionary = GameData.monsters[mid]
		if bool(m.get("boss", false)) or bool(m.get("miniboss", false)) or not m.has("lv"):
			continue
		var dd := absi(int(m["lv"]) - lv)
		if dd < bd:
			bd = dd
			best = m
	return best


static func _dps(c, mon: Dictionary) -> float:
	var p := clampf(float(c.crit_rate()) / 100.0, 0.0, 1.0)
	var m := float(CombatV2.crit_mult(CombatV2.crit_dmg_rating(c), 0.0))
	if str(c.job) == "magic_control":
		var matk := float(c.matk_min() + c.matk_max()) * 0.5 * float(c.matk_rate())
		return matk * float(c.card_mult(mon))
	return float(c.atk_display()) * (1.0 + p * (m - 1.0)) * float(c.card_mult(mon)) / maxf(0.02, float(c.attack_delay()))


static func _ehp(c, mon: Dictionary) -> float:
	var red := (100.0 - float(c.hard_def())) / 100.0
	red *= (100.0 - float(c.card_pct("sub_race", str(mon.get("race", ""))))) / 100.0
	red *= (100.0 - float(c.sub_ele_pct("neutral"))) / 100.0
	var hitc := clampf(80.0 + float(int(mon.get("lv", 1)) + int(mon.get("dex", mon.get("lv", 1)))) - float(c.flee()), 5.0, 100.0) / 100.0
	return float(c.max_hp()) / maxf(0.01, red * hitc)


static func _metric(c, mon: Dictionary, kind: String) -> float:
	match kind:
		"br":
			return float(CombatV2.battle_rating(c))
		"dps":
			return _dps(c, mon)
	return _ehp(c, mon)


## Fills every worn piece with its max grade of SS lines, greedily picking the line that raises `kind` the most
## (rules respected; keyed lines only for the reference monster's race / element / size / neutral). Returns the share.
static func _worst_share(c, mon: Dictionary, kind: String) -> float:
	for slot in c.equipment:
		var inst: Dictionary = c.equipment[slot]
		inst.erase("grade")
		inst.erase("opts")
	GearOpts.mode = 2
	var base := _metric(c, mon, kind)
	GearOpts.mode = 0
	var keys_ok := [str(mon.get("race", "")), str(mon.get("element", "")), str(mon.get("size", "")), "neutral"]
	for slot in c.equipment:
		var inst2: Dictionary = c.equipment[slot]
		var mg := GearOpts.max_grade(str(inst2["id"]))
		if mg > 0:
			inst2["grade"] = mg
			inst2["opts"] = []
	for round_i in 4:
		for slot in c.equipment:
			var inst3: Dictionary = c.equipment[slot]
			var g := GearOpts.grade_of(inst3)
			var opts: Array = GearOpts.opts_of(inst3)
			if opts.size() >= GearOpts.grade_lines(g):
				continue
			var id := str(inst3["id"])
			var best_o: Dictionary = {}
			var best_v := -1.0
			for s in GearOpts.allowed(id, opts):
				var sk := GearOpts.sub_key(str(s))
				if sk != "" and not keys_ok.has(sk):
					continue
				var o := {"stat": str(s), "val": GearOpts.stat_max(str(s), GearOpts.item_lv(id)), "tier": 4}
				opts.append(o)
				var v := _metric(c, mon, kind)
				opts.pop_back()
				if v > best_v:
					best_v = v
					best_o = o
			if not best_o.is_empty():
				opts.append(best_o)
	var full := _metric(c, mon, kind)
	return (full - base) / maxf(0.001, base)


static func _cap_checks() -> void:
	var cap := float(GearOpts.data().get("cap", {}).get("share", 0.10))
	var worst := {"br": 0.0, "dps": 0.0, "ehp": 0.0}
	var all_ok := true
	var rows: Array = []
	var peak := 0.0
	for job in ["defend_counter", "hunt", "magic_control"]:
		for lv in [15, 45, 75, 105, 140]:
			var mon := _ref_mon(lv)
			var line := "%s Lv%d:" % [job, lv]
			for kind in ["br", "dps", "ehp"]:
				var sum := 0.0
				var hi := 0.0
				for off in [0, 3, 6, 9]:
					var sh1 := _worst_share(_ref_char(job, lv, off), mon, kind)
					sum += sh1
					hi = maxf(hi, sh1)
				var sh := sum / 4.0
				peak = maxf(peak, hi)
				worst[kind] = maxf(float(worst[kind]), sh)
				all_ok = all_ok and sh <= cap + 0.0001
				line += " %s +%.1f%% (peak %.1f)" % [kind, sh * 100.0, hi * 100.0]
			rows.append(line)
	for r in rows:
		print("    gearopt cap ", r)
	if _arg("--gearoptdiag") != "":
		_diag()
	check(all_ok, "POWER CAP: every SS line on every piece <= +%d%% (worst BR +%.1f%%, damage +%.1f%%, EHP +%.1f%%)" % [roundi(cap * 100.0), worst["br"] * 100.0, worst["dps"] * 100.0, worst["ehp"] * 100.0])
	check(peak <= cap + 0.05, "even right below a stat step the full SS set stays under +%d%% (peak +%.1f%%)" % [roundi((cap + 0.05) * 100.0), peak * 100.0])
	GearOpts.mode = 0


# ---------------------------------------------------------------- UI

static func _ui_checks(main: Node) -> void:
	var hud = main.hud
	var ps = PlayerState
	var wid := _pick("weapon", 90, 200)
	var insts: Array = []
	for g in 5:
		var inst: Dictionary = CharacterState.make_inst(wid)
		if g > 0:
			var opts: Array = []
			var rng := RandomNumberGenerator.new()
			rng.seed = 100 + g
			for i in GearOpts.grade_lines(g):
				opts.append(GearOpts.roll_line(wid, opts, rng, mini(4, i + g - 1)))
			GearOpts.apply(inst, {"grade": g, "opts": opts})
		ps.ch.gear.append(inst)
		insts.append(inst)
	var ok_rows := true
	var ok_col := true
	for g in 5:
		var tip: Control = hud.item_tooltip({"id": wid, "inst": insts[g], "qty": 1})
		var rp: Node = tip.find_child("TipRunes", true, false)
		if g == 0:
			ok_rows = ok_rows and rp == null
		else:
			ok_rows = ok_rows and rp != null and int(rp.get_meta("rune_rows", -1)) == g
			var nm: Node = tip.find_child("TipName", true, false)
			ok_col = ok_col and nm != null and (nm as Label).get_theme_color("font_color").is_equal_approx(GearOpts.grade_color(g))
		tip.free()
	check(ok_rows, "tooltip: a rune panel with one row per line (none on white)")
	check(ok_col, "tooltip: the name is coloured by grade")
	check(hud.item_frame(wid, insts[4]).is_equal_approx(GearOpts.grade_color(4)), "bag slot frame takes the grade colour")
	var shot := _arg("--gearoptshots")
	if shot != "" and DisplayServer.get_name() != "headless":
		await _sheet(main, wid, insts, shot)
	for inst in insts:
		ps.ch.gear.erase(inst)
	ps.ch.changed.emit()


## One PNG: the tooltip of the same piece in the 5 grades side by side (cropped from the screen one by one).
static func _sheet(main: Node, wid: String, insts: Array, path: String) -> void:
	var hud = main.hud
	var crops: Array = []
	for g in insts.size():
		var p := PanelContainer.new()
		p.add_theme_stylebox_override("panel", hud.theme_.get_stylebox("panel", "TooltipPanel"))
		p.add_child(hud.item_tooltip({"id": wid, "inst": insts[g], "qty": 1}))
		hud.ui_root.add_child(p)
		p.position = Vector2(24, 16)
		await SelfTest.frames(main, 10)
		var img: Image = main.get_viewport().get_texture().get_image()
		var vs: Vector2 = main.get_viewport().get_visible_rect().size
		var sc := float(img.get_width()) / maxf(1.0, vs.x)
		var r := p.get_global_rect()
		var rr := Rect2i(int(r.position.x * sc), int(r.position.y * sc), int(r.size.x * sc), int(r.size.y * sc)).intersection(Rect2i(0, 0, img.get_width(), img.get_height()))
		crops.append(img.get_region(rr))
		p.queue_free()
		await SelfTest.frames(main, 2)
	var gap := 16
	var w := gap
	var h := 0
	for im in crops:
		w += (im as Image).get_width() + gap
		h = maxi(h, (im as Image).get_height())
	var sheet := Image.create(w, h + gap * 2, false, Image.FORMAT_RGBA8)
	sheet.fill(Color("#2b2118"))
	var x := gap
	for im in crops:
		var ii: Image = im
		ii.convert(Image.FORMAT_RGBA8)
		sheet.blit_rect(ii, Rect2i(0, 0, ii.get_width(), ii.get_height()), Vector2i(x, gap))
		x += ii.get_width() + gap
	sheet.save_png(path)
	print("GEAROPTSHOT ", path, " ", sheet.get_size())


## --gearoptdiag=1: share of each stat alone at its total cap (tuning aid).
static func _diag() -> void:
	for job in ["defend_counter", "hunt", "magic_control"]:
		for lv in [15, 75, 140]:
			var c := _ref_char(job, lv)
			var mon := _ref_mon(lv)
			var keys_ok := [str(mon.get("race", "")), str(mon.get("element", "")), str(mon.get("size", "")), "neutral"]
			var slot0 := "weapon" if c.equipment.has("weapon") else str(c.equipment.keys()[0])
			for kind in ["br", "dps", "ehp"]:
				GearOpts.mode = 2
				var base := _metric(c, mon, kind)
				GearOpts.mode = 0
				var parts: Array = []
				for fam in GearOpts.data()["stats"]:
					var d: Dictionary = GearOpts.data()["stats"][fam]
					var sid := str(fam)
					if d.has("keys"):
						var kk := ""
						for k in GearOpts.data()["keys"][str(d["keys"])]:
							if keys_ok.has(str(k)):
								kk = str(k)
						if kk == "":
							continue
						sid = "%s:%s" % [fam, kk]
					var tot := GearOpts.stat_total(sid, lv)
					if tot <= 0:
						tot = GearOpts.stat_max(sid, lv)
					var inst: Dictionary = c.equipment[slot0]
					inst["grade"] = 4
					inst["opts"] = [{"stat": sid, "val": tot, "tier": 4}]
					var v := _metric(c, mon, kind)
					inst.erase("grade")
					inst.erase("opts")
					var sh := (v - base) / maxf(0.001, base) * 100.0
					if sh >= 0.3:
						parts.append([sh, "%s %.1f" % [sid, sh]])
				parts.sort_custom(func(a, b): return a[0] > b[0])
				var txt: Array = []
				for e in parts:
					txt.append(e[1])
				print("    gearopt diag %s Lv%d %s: %s" % [job, lv, kind, ", ".join(txt)])
