extends RefCounted
## New-world quest lines (2026-10-23, docs/CHECKPOINT_2026-10-22.md section 2.10) - selftest --only=realmquests, also in
## the full run. Skysunpia / Underworld / Land of Smile / Soul Volcano each have:
##  - a main story chain ("chain": "<w>_story", 8-12 steps, herald) through the world's maps in level order to the world
##    MVP (Lv 200), item hunts / mini-boss / dungeon MVP / visit steps;
##  - side quests from the town guide, inn and refiner;
##  - daily item hunts on the bounty / notice board ("repeat": "daily", quest_log.gd today()).
## Checks:
## Trim (Boss 2026-10-23): 8 story steps, 3 side, 3 dailies per world; retired ids in quests.json "retired".
##  1. data: every target / item / drop monster / place exists and belongs to the quest's world, hunt items are bound
##     0-weight quest items of that world, Thai for every text, the cultural word rule (thai_soul_test.gd BANNED);
##  2. rewards stay on the curve of the older quests (base EXP / E(L), E = median kill EXP of the world's normal monsters
##     within 6 levels), no gold / item loop (no reward is a quest item or a quest target, dailies small, no give / cost);
##  3. the "???" rule: a new world's quests cannot be taken and are named "???" until the character has found that world;
##  4. every quest is completable on a test character (accept -> AUTO's goal = the quest map + its monsters / places ->
##     objective -> AUTO's goal = the turn-in NPC in the world's town -> turned in, rewards paid); dailies come back the
##     next day without growing the done list;
##  5. AUTO-quest runs the first story steps for real (Skysunpia 1-4 across three maps, step 1 of the other worlds).

const SelfTest = preload("res://scripts/selftest.gd")
const Realms = preload("res://scripts/realms.gd")
const QuestLog = preload("res://scripts/quest_log.gd")
const AutoPlay = preload("res://scripts/auto_play.gd")
const QS = preload("res://scripts/ui/quest_steps.gd")
const CharacterState = preload("res://scripts/server/character_state.gd")
const ThaiSoulTest = preload("res://scripts/thai_soul_test.gd")

const WORLDS := {
	"sky": {"town": "sky_nimbaria", "tour": "nimbaria_tour", "chain": "sky_story"},
	"sea": {"town": "sea_coralia", "tour": "coralia_tour", "chain": "sea_story"},
	"land_of_smile": {"town": "smile_ban_sabai", "tour": "bansabai_tour", "chain": "smile_story"},
	"soul_volcano": {"town": "soul_lanternrest", "tour": "lanternrest_tour", "chain": "soul_story"},
}
const CULTURE := ["land_of_smile", "soul_volcano"]
## base EXP / E(L) bounds (gen_quests.py: story hunt 20, visit 10, mini 15, dungeon MVP 30, world MVP 40, side 12-15,
## daily 10; the older herald / board quests sit at ~12-25)
const RATIO_MIN := 5.0
const RATIO_MAX := 45.0
const RATIO_DAILY := 12.0
const SPEED := 6.0


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


static func run(main: Node) -> void:
	print("SELFTEST realmquests")
	var keep_force := Realms.force
	Realms.force = 0
	data_tests()
	hide_tests()
	logic_tests()
	Realms.force = keep_force
	await live_tests(main)


# ---------------------------------------------------------------- helpers

static func realm_quests(realm: String) -> Array:
	var out: Array = []
	for q in GameData.quest_list:
		if QuestLog.realm_of(str(q["id"])) == realm:
			out.append(q)
	return out


static func npc(id: String) -> Dictionary:
	for n in GameData.npcs:
		if str(n.get("id", "")) == id:
			return n
	return {}


## E(L): median kill EXP of the realm's normal monsters within 6 levels of `lv` (the nearest one when none).
static func curve(realm: String, lv: int) -> float:
	var pool: Array = []
	var best := 0
	var bd := 9999
	for mid in GameData.monsters:
		var m: Dictionary = GameData.monsters[mid]
		if str(m.get("realm", "")) != realm or bool(m.get("boss", false)) or bool(m.get("miniboss", false)) or bool(m.get("mvp", false)):
			continue
		var d := absi(int(m.get("lv", 0)) - lv)
		if d <= 6:
			pool.append(int(m.get("exp", 0)))
		if d < bd:
			bd = d
			best = int(m.get("exp", 0))
	if pool.is_empty():
		return float(best)
	pool.sort()
	var n := pool.size()
	return float(pool[n / 2]) if n % 2 == 1 else (float(pool[n / 2 - 1]) + float(pool[n / 2])) * 0.5


static func on_map(map_id: String, mid: String) -> bool:
	for z in GameData.map(map_id).get("zones", []):
		for e in z.get("mobs", []):
			if str(e["id"]) == mid:
				return true
	return false


static func targets_of_quests() -> Dictionary:
	var out := {}
	for q in GameData.quest_list:
		if str(q.get("type", "")) in ["collect", "deliver"]:
			out[str(q.get("target", ""))] = true
	return out


# ---------------------------------------------------------------- 1 + 2. data, rewards, culture

static func data_tests() -> void:
	var th = JSON.parse_string(FileAccess.get_file_as_string("res://data/i18n_th.json"))
	if not (th is Dictionary):
		th = {}
	var targets := targets_of_quests()
	for realm in WORLDS:
		var spec: Dictionary = WORLDS[realm]
		var town: String = spec["town"]
		var qs := realm_quests(realm)
		var bad: Array = []
		var rbad: Array = []
		var cult: Array = []
		var givers := {}
		for q in qs:
			var id := str(q["id"])
			var g := npc(str(q.get("giver", "")))
			givers[str(g.get("role", ""))] = int(givers.get(str(g.get("role", "")), 0)) + 1
			if g.is_empty() or Realms.of(str(g.get("map", ""))) != realm:
				bad.append(id + ":giver")
			var ti := npc(QuestLog.turn_in_npc(id))
			if ti.is_empty() or str(ti.get("map", "")) != town:
				bad.append(id + ":turn-in not in town")
			var mid := str(q.get("map", ""))
			if int(q.get("min_lv", 0)) < 50 or GameData.map(mid).is_empty() or Realms.of(mid) != realm:
				bad.append(id + ":lv/map")
			match str(q.get("type", "")):
				"kill":
					var t := str(q.get("target", ""))
					var md: Dictionary = GameData.monsters.get(t, {})
					if md.is_empty() or md.has("placeholder") or t.begins_with("ph_") or str(md.get("realm", "")) != realm or not on_map(mid, t):
						bad.append(id + ":kill target")
				"collect":
					var it: Dictionary = GameData.item(str(q.get("target", "")))
					var dr: Dictionary = q.get("drops", {})
					if it.is_empty():
						bad.append(id + ":no item")
					if not dr.is_empty():
						if not (bool(it.get("quest_item", false)) and bool(it.get("no_sell", false)) and bool(it.get("no_trade", false))
								and float(it.get("weight", 1)) == 0.0 and int(it.get("price", 1)) == 0 and str(it.get("realm", "")) == realm):
							bad.append(id + ":hunt item not a bound 0-weight quest item of the world")
						for hm in dr:
							var hd: Dictionary = GameData.monsters.get(str(hm), {})
							if hd.is_empty() or str(hd.get("realm", "")) != realm or bool(hd.get("boss", false)) or not on_map(mid, str(hm)) \
									or float(dr[hm]) <= 0.0 or float(dr[hm]) > 1.0:
								bad.append("%s:drop %s" % [id, hm])
					elif AutoPlay.droppers(str(q.get("target", ""))).is_empty():
						bad.append(id + ":nothing drops it")
				"visit":
					var half := float(GameData.map(mid).get("size", 140)) / 2.0
					for pl in q.get("places", []):
						if absf(float(pl[1])) > half - 2.0 or absf(float(pl[2])) > half - 2.0 or not th.has(str(pl[0])):
							bad.append("%s:place %s" % [id, pl[0]])
				_:
					bad.append(id + ":type")
			for k in ["name", "text", "done_text"]:
				if not th.has(str(q.get(k, ""))) and not (k == "name" and str(q.get("name_th", "")) != ""):
					bad.append("%s:th %s" % [id, k])
			# rewards on the curve, no loops
			var rw: Dictionary = q.get("rewards", {})
			var lv := int(q.get("min_lv", 50))
			var e := curve(realm, lv)
			var ratio := float(rw.get("base_exp", 0)) / maxf(1.0, e)
			var daily := str(q.get("repeat", "")) == "daily"
			# (the town tours are a short walk round the plaza: off the curve on purpose)
			if mid != town and (ratio < RATIO_MIN or ratio > (RATIO_DAILY if daily else RATIO_MAX)):
				rbad.append("%s:exp %.1fxE" % [id, ratio])
			if int(rw.get("job_exp", 0)) > int(rw.get("base_exp", 0)) or int(rw.get("zeny", 0)) > (150 if daily else 800) * lv:
				rbad.append(id + ":job/zeny")
			for k in rw.get("items", {}):
				var ri: Dictionary = GameData.item(str(k))
				if ri.is_empty() or bool(ri.get("quest_item", false)) or targets.has(str(k)) or int(rw["items"][k]) > 5:
					rbad.append("%s:reward %s" % [id, k])
			if daily and (q.has("give") or q.has("cost") or rw.has("bag_slots") or rw.has("unlock_text") or int(rw.get("shards", 99)) > 1
					or str(q.get("type", "")) != "collect" or not q.has("drops")):
				rbad.append(id + ":daily shape")
			if q.has("give") and str(q.get("type", "")) != "deliver":
				rbad.append(id + ":gives items")
			# the cultural rule (Land of Smile / Soul Volcano): quest + hunt item strings, English and Thai
			if realm in CULTURE:
				var strs: Array = [str(q.get("name", "")), str(q.get("name_th", "")), str(q.get("text", "")), str(q.get("done_text", "")),
					str(th.get(str(q.get("text", "")), "")), str(th.get(str(q.get("done_text", "")), ""))]
				if str(q.get("type", "")) == "collect":
					var it2: Dictionary = GameData.item(str(q.get("target", "")))
					strs.append_array([str(it2.get("name", "")), str(it2.get("name_th", "")), str(it2.get("desc", "")), str(it2.get("desc_th", ""))])
				for s in strs:
					for w in ThaiSoulTest.BANNED:
						if s.to_lower().contains(w):
							cult.append("%s (%s)" % [id, w])
		check(bad.is_empty(), "%s: %d quests, every target / item / monster / place is real and of this world, Thai for every text %s" % [realm, qs.size(), str(bad)])
		check(rbad.is_empty(), "%s: rewards on the curve (%.0f-%.0fx E(L), dailies <= %.0fx, gold <= 800 x Lv), no quest item / quest target as a reward, no gold loop %s" % [realm, RATIO_MIN, RATIO_MAX, RATIO_DAILY, str(rbad)])
		if realm in CULTURE:
			check(cult.is_empty(), "%s: no religious / royal words in any quest or quest item %s" % [realm, str(cult)])
		# Boss 2026-10-23 trim: per world 8 story steps + 3 side (guide / inn / refiner) + 3 dailies = 14 new quests
		var fresh: int = qs.filter(func(q): return str(q.get("realm", "")) == realm).size()
		check(fresh == 14, "%s: 14 new-world quests after the trim (8 story + 3 side + 3 daily), %d" % [realm, fresh])
		check(int(givers.get("guide", 0)) >= 1 and int(givers.get("heal", 0)) >= 1 and int(givers.get("refine", 0)) >= 1,
			"%s: side quests from the guide, inn and refiner (%s)" % [realm, str(givers)])
		# the story chain
		var chain: Array = qs.filter(func(q): return str(q.get("chain", "")) == str(spec["chain"]))
		chain.sort_custom(func(a, b): return int(a.get("step", 0)) < int(b.get("step", 0)))
		var cbad: Array = []
		var prev := str(spec["tour"])
		var lv_prev := 0
		var map_lv_prev := 0
		var maps_seen := {}
		for i in chain.size():
			var q: Dictionary = chain[i]
			var id := str(q["id"])
			var mlv := int((GameData.map(str(q["map"])).get("level_range", [0, 0]) as Array)[0])
			maps_seen[str(q["map"])] = true
			if int(q.get("step", 0)) != i + 1 or q.get("requires", []) != [prev] or str(npc(str(q["giver"])).get("role", "")) != "quest":
				cbad.append(id + ":order")
			if int(q["min_lv"]) < lv_prev or mlv < map_lv_prev or int(q["min_lv"]) < mlv - 12 or int(q["min_lv"]) > mlv + 10:
				cbad.append("%s:level (Lv %d, map %d)" % [id, int(q["min_lv"]), mlv])
			prev = id
			lv_prev = int(q["min_lv"])
			map_lv_prev = mlv
		var last: Dictionary = chain[chain.size() - 1] if not chain.is_empty() else {}
		var mvp: Dictionary = GameData.monsters.get(str(last.get("target", "")), {})
		check(chain.size() == 8 and cbad.is_empty() and maps_seen.size() >= 8,
			"%s: a %d-step story chain from the herald through %d maps in level order %s" % [realm, chain.size(), maps_seen.size(), str(cbad)])
		check(str(last.get("type", "")) == "kill" and bool(mvp.get("mvp", false)) and int(mvp.get("lv", 0)) == 200 and Realms.of(str(last.get("map", ""))) == realm,
			"%s: the chain ends at the world MVP (%s Lv %d)" % [realm, str(last.get("target", "")), int(mvp.get("lv", 0))])
		# the board's dailies
		var board := ""
		for n in GameData.npcs:
			if str(n.get("map", "")) == town and str(n.get("role", "")) == "board":
				board = str(n["id"])
		var dailies: Array = qs.filter(func(q): return str(q.get("giver", "")) == board and str(q.get("repeat", "")) == "daily")
		var dl := {}
		for q in dailies:
			dl[int(q["min_lv"]) / 25] = true
		check(dailies.size() == 3 and dl.size() == 3, "%s: the board posts %d daily item hunts across the level range" % [realm, dailies.size()])


# ---------------------------------------------------------------- 3. hidden until the world is found

static func hide_tests() -> void:
	var c = CharacterState.new()
	c.new_character("RqHide")
	c.base_lv = 200
	var keep_ch = PlayerState.ch
	var keep_force := Realms.force
	var keep_view = Realms.view_as
	for realm in WORLDS:
		var spec: Dictionary = WORLDS[realm]
		c.realms_seen = {}
		if not c.quests.done.has(str(spec["tour"])):
			c.quests.done.append(str(spec["tour"]))
		var first := str(spec["chain"]) + "_01"
		var tour := str(spec["tour"])
		var why_before: String = c.quests.can_accept(c, first)
		var why_tour: String = c.quests.can_accept(c, "%s_daily_1" % str(spec["chain"]).split("_")[0])
		Realms.force = 1
		Realms.view_as = c
		var nm_before: String = QS.quest_name(first)
		var tour_name: String = QS.quest_name(tour)
		c.realms_seen = {realm: 1}
		var nm_after: String = QS.quest_name(first)
		Realms.force = 0
		Realms.view_as = keep_view
		var why_after: String = c.quests.can_accept(c, first)
		check(why_before == "???" and why_tour == "???" and nm_before == "???" and tour_name == "???" and why_after == "" and nm_after != "???",
			"%s: its quests are ??? (not offered, name hidden) until the world is found, then open (%s / %s -> %s / %s)" % [realm, why_before, nm_before, why_after, nm_after])
	# main-world quests are untouched by the rule
	Realms.force = 1
	Realms.view_as = c
	check(QS.quest_name("slime_trouble") != "???" and QuestLog.realm_of("slime_trouble") == "main" and QuestLog.realm_of("nimbaria_tour") == "sky",
		"main-world quests are never hidden; older realm quests find their world through their map / giver")
	Realms.force = keep_force
	Realms.view_as = keep_view
	PlayerState.ch = keep_ch


# ---------------------------------------------------------------- 4. completable + AUTO goals + dailies

static func logic_tests() -> void:
	var keep_ch = PlayerState.ch
	var keep_day := QuestLog.day_override
	QuestLog.day_override = 20000
	for realm in WORLDS:
		var spec: Dictionary = WORLDS[realm]
		var c = CharacterState.new()
		c.new_character("RqTest")
		c.realms_seen = {realm: 1}
		c.quests.done.append(str(spec["tour"]))
		PlayerState.ch = c
		var qs := realm_quests(realm)
		# the story first, in order (each step needs the one before), then the rest
		qs.sort_custom(func(a, b): return (0 if str(a.get("chain", "")) != "" else 1) * 1000 + int(a.get("step", 0)) < (0 if str(b.get("chain", "")) != "" else 1) * 1000 + int(b.get("step", 0)))
		var bad: Array = []
		var done_n := 0
		for q in qs:
			var id := str(q["id"])
			if c.quests.is_done(id):
				continue
			c.base_lv = maxi(int(c.base_lv), int(q.get("min_lv", 1)))
			c.map_id = str(q.get("map", ""))
			if not c.quests.accept(c, id):
				bad.append(id + ":accept " + c.quests.can_accept(c, id))
				continue
			var g: Dictionary = AutoPlay.quest_goal(id)
			var typ := str(q.get("type", ""))
			var want := "visit" if typ == "visit" else "kill"
			var mobs: Array = g.get("mobs", [])
			if str(g.get("kind", "")) != want or str(g.get("map", "")) != str(q.get("map", "")):
				bad.append("%s:AUTO goal %s on %s" % [id, str(g.get("kind", "")), str(g.get("map", ""))])
			elif typ == "kill" and not (str(q["target"]) in mobs):
				bad.append(id + ":AUTO hunts the wrong monsters")
			elif typ == "collect" and not (q.get("drops", {}) as Dictionary).keys().all(func(k): return str(k) in mobs):
				bad.append(id + ":AUTO hunts the wrong monsters")
			# the objective
			match typ:
				"kill":
					for i in int(q.get("count", 1)):
						c.quests.on_kill(c, str(q["target"]))
				"collect":
					var dr: Dictionary = q.get("drops", {})
					if dr.is_empty():
						# an older plain collect quest: the monsters' own drops
						c.add_item(str(q["target"]), c.quests.goal(id))
					else:
						# the hunt itself: the quest's monsters die one after another until the goal (real drop chances)
						var have0: int = c.count(str(q["target"]))
						var rolls := 0
						while c.count(str(q["target"])) < c.quests.goal(id) and rolls < 400:
							c.quests.roll_hunt(c, str(dr.keys()[rolls % dr.size()]))
							rolls += 1
						# a kill past the goal gives nothing more (no farming the bound items)
						var extra: Array = c.quests.roll_hunt(c, str(dr.keys()[0]))
						if c.count(str(q["target"])) != c.quests.goal(id) or not extra.is_empty() or have0 != 0:
							bad.append("%s:hunt stops at the goal (%d / %d)" % [id, c.count(str(q["target"])), c.quests.goal(id)])
						if c.sell_price(str(q["target"])) != 0:
							bad.append(id + ":hunt item sells")
				"visit":
					for pl in q.get("places", []):
						c.quests.check_visits(c, Vector3(float(pl[1]), 0, float(pl[2])))
			var g2: Dictionary = AutoPlay.quest_goal(id)
			var ti := npc(QuestLog.turn_in_npc(id))
			if not c.quests.is_complete(c, id) or str(g2.get("kind", "")) != "turnin" or str(g2.get("npc", "")) != str(ti.get("id", "")) or str(g2.get("map", "")) != str(spec["town"]):
				bad.append("%s:not complete / AUTO turn-in %s" % [id, str(g2)])
				continue
			var z0: int = c.zeny
			var e0: int = int(c.base_exp) + int(c.base_lv) * 1000000000
			var rw: Dictionary = q.get("rewards", {})
			if not c.quests.complete(c, id) or c.zeny != z0 + int(rw.get("zeny", 0)) or int(c.base_exp) + int(c.base_lv) * 1000000000 <= e0:
				bad.append(id + ":turn-in / rewards")
				continue
			for k in rw.get("items", {}):
				if c.count(str(k)) < int(rw["items"][k]):
					bad.append("%s:reward %s" % [id, k])
			if typ == "collect" and c.count(str(q["target"])) != 0:
				bad.append(id + ":hunt items left in the bag")
			done_n += 1
			# dailies: closed for today, open tomorrow, the done list does not grow
			if str(q.get("repeat", "")) == "daily":
				var n_done: int = c.quests.done.size()
				var why: String = c.quests.can_accept(c, id)
				QuestLog.day_override += 1
				var why2: String = c.quests.can_accept(c, id)
				var acc: bool = c.quests.accept(c, id)
				c.quests._give(c, str(q["target"]), c.quests.goal(id))
				var again: bool = c.quests.complete(c, id)
				var saved: Dictionary = c.quests.to_dict()
				var ql2 = QuestLog.new()
				ql2.from_dict(JSON.parse_string(JSON.stringify(saved)))
				if why == "" or why2 != "" or not acc or not again or c.quests.done.size() != n_done or int(ql2.daily.get(id, -1)) != QuestLog.today() \
						or ql2.can_accept(c, id) == "":
					bad.append("%s:daily (%s / %s / %s / %s)" % [id, why, why2, str(acc), str(again)])
		check(bad.is_empty() and done_n == qs.size() - 1, "%s: all %d quests completable on a test character - AUTO goal on the quest map, objective, AUTO back to the town NPC, turned in, rewards paid; dailies once a day %s" % [realm, done_n, str(bad)])
	QuestLog.day_override = keep_day
	PlayerState.ch = keep_ch
	# an old save without "daily" loads fine
	var ql = QuestLog.new()
	ql.from_dict({"active": {}, "done": ["slime_trouble"]})
	check(ql.daily.is_empty() and ql.is_done("slime_trouble"), "old quest save (no daily block) loads")
	migration_tests()


## A b49 save made before the trim (96 quests): retired quests in active / done / daily are dropped, kept ones stay,
## nothing in the bag is touched, and the herald offers the next kept story step straight away.
static func migration_tests() -> void:
	var gone: Dictionary = QuestLog.retired_ids()
	var stray: Array = []
	for id in gone:
		if not GameData.quest(str(id)).is_empty():
			stray.append(id)
	check(gone.size() == 40 and stray.is_empty() and gone.has("sky_story_02") and gone.has("soul_daily_5") and gone.has("sea_side_inn_1"),
		"trim: 40 retired quest ids listed, none still defined %s" % str(stray))
	var c = CharacterState.new()
	c.new_character("RqOld")
	c.base_lv = 120
	c.realms_seen = {"sky": 1, "soul_volcano": 1}
	var old_save := {"active": {"sky_story_02": {"n": 0, "seen": []}, "sky_side_guide_2": {"n": 0, "seen": []}, "soul_story_04": {"n": 0, "seen": [1]}},
		"done": ["nimbaria_tour", "sky_story_01", "lanternrest_tour", "soul_story_01", "soul_story_02", "soul_story_03", "soul_daily_2"],
		"daily": {"soul_daily_2": 19000, "soul_daily_1": 19000}}
	c.inventory["sky_q_roc_down"] = 5
	c.inventory["soul_q_light_mote"] = 3
	var inv0: Dictionary = (c.inventory as Dictionary).duplicate()
	c.quests.from_dict(JSON.parse_string(JSON.stringify(old_save)))
	var ql = c.quests
	var ok_active: bool = ql.active.keys() == ["soul_story_04"] and (ql.active["soul_story_04"]["seen"] as Array) == [1]
	var ok_done: bool = not ql.done.has("sky_story_02") and not ql.done.has("soul_story_02") and not ql.done.has("soul_daily_2") and ql.done.has("soul_story_03") and ql.done.has("sky_story_01")
	var ok_daily: bool = not ql.daily.has("soul_daily_2") and ql.daily.has("soul_daily_1")
	check(ok_active and ok_done and ok_daily and c.inventory == inv0,
		"old save: retired quests dropped from active / done / daily, kept ones (progress too) stay, bag untouched (%s / %s / %s)" % [str(ql.active.keys()), str(ql.done), str(ql.daily)])
	var keep_day := QuestLog.day_override
	QuestLog.day_override = 20000
	check(ql.can_accept(c, "sky_story_03") == "" and ql.can_accept(c, "soul_daily_1") == "" and ql.offers(c, "sky_nimbaria_quest").has("sky_story_03"),
		"old save: the herald offers the next kept step (sky_story_03 after sky_story_01) and old dailies come back")
	QuestLog.day_override = keep_day
	# the retired hunt items stay defined (old bags), are not needed by any quest any more and can be thrown away
	var Bag = load("res://scripts/server/bag.gd")
	var it: Dictionary = GameData.item("sky_q_roc_down")
	check(not it.is_empty() and bool(it.get("retired", false)) and str(Bag.blocked(c, "sky_q_roc_down")) == "" and c.sell_price("sky_q_roc_down") == 0,
		"retired hunt items: still defined, discardable, worth nothing")


# ---------------------------------------------------------------- 5. AUTO-quest for real

## The story chain of `realm` in step order (ids keep their pre-trim numbers: sky_story_01, _03, _04, _06 ...).
static func _chain_ids(realm: String) -> Array:
	var chain: Array = realm_quests(realm).filter(func(q): return str(q.get("chain", "")) == str(WORLDS[realm]["chain"]))
	chain.sort_custom(func(a, b): return int(a.get("step", 0)) < int(b.get("step", 0)))
	return chain.map(func(q): return str(q["id"]))


static func _fast(on: bool) -> void:
	Engine.time_scale = SPEED if on else 1.0
	Engine.physics_ticks_per_second = int(60 * SPEED) if on else 60
	Engine.max_physics_steps_per_frame = 64 if on else 8


static func live_tests(main: Node) -> void:
	if main.auto == null or main.hud == null:
		check(false, "live: AUTO / HUD present")
		return
	var c = PlayerState.ch
	if str(c.job) == "novice":
		SelfTest.make_job(main, "swordman")
		c = PlayerState.ch
	var keep := {"base_lv": c.base_lv, "base_exp": c.base_exp, "job_lv": c.job_lv, "job_exp": c.job_exp, "stat_points": c.stat_points,
		"skill_points": c.skill_points, "stats": (c.stats as Dictionary).duplicate(), "zeny": c.zeny, "inventory": (c.inventory as Dictionary).duplicate(true),
		"quests": JSON.parse_string(JSON.stringify(c.quests.to_dict())), "realms_seen": (c.realms_seen as Dictionary).duplicate()}
	var keep_dmg = GameData.config.get("player_dmg_rate", 1)
	var keep_drops := {}
	c.base_lv = 90
	for s in ["str", "agi", "vit", "dex"]:
		c.stats[s] = 120
	GameData.config["player_dmg_rate"] = float(keep_dmg) * 20.0
	_fast(true)
	var au = main.auto
	var runs := {"sky": 4, "sea": 1, "land_of_smile": 1, "soul_volcano": 1}
	for realm in runs:
		var spec: Dictionary = WORLDS[realm]
		main.load_map(str(spec["town"]))
		var arrived: bool = await SelfTest.wait_map(main, str(spec["town"]))
		await SelfTest.frames(main, 10)
		check(arrived and Realms.has_seen(c, realm), "live %s: in %s, the world is found on arrival" % [realm, str(spec["town"])])
		if not c.quests.is_done(str(spec["tour"])):
			c.quests.done.append(str(spec["tour"]))
		for step in int(runs[realm]):
			var id: String = str(_chain_ids(realm)[step])
			var q: Dictionary = GameData.quest(id)
			# the hunt rolls always hit here (the drop chance is the data test's business), so the run stays short
			if q.has("drops"):
				keep_drops[id] = (q["drops"] as Dictionary).duplicate()
				for k in q["drops"]:
					q["drops"][k] = 1.0
			var r: Dictionary = main.send({"t": "quest_accept", "id": id})
			var acc: bool = bool(r.get("ok", false)) and c.quests.is_active(id)
			au.start_quest(id)
			var restarts := 0
			var t0 := Time.get_ticks_msec()
			var frames := 0
			var pe = main.me()
			while frames < 30000:
				await main.get_tree().physics_frame
				frames += 1
				pe = main.me()
				if pe != null and pe.dead:
					pe.dead = false
				if c.hp < c.max_hp():
					c.hp = c.max_hp()
				if pe != null and pe.get("ch") != null and pe.ch != c and pe.ch.hp < pe.ch.max_hp():
					pe.ch.hp = pe.ch.max_hp()
				if c.quests.is_done(id) and not au.active:
					break
				if not au.active and c.quests.is_active(id) and restarts < 4:
					# a death / a stop on the way: press Auto-quest again, like a player would
					restarts += 1
					au.start_quest(id)
			if keep_drops.has(id):
				q["drops"] = keep_drops[id]
			check(acc and c.quests.is_done(id) and main.map_id == str(spec["town"]),
				"live %s: AUTO-quest did \"%s\" (%s on %s) and turned it in at %s (%d frames, %.0f s, %d restarts)" % [realm, str(q.get("name", id)),
				str(q.get("type", "")), str(q.get("map", "")), str(main.map_id), frames, (Time.get_ticks_msec() - t0) / 1000.0, restarts])
			if not c.quests.is_done(id):
				if au.active:
					au.stop("Auto-quest test over.", false)
				break
		SelfTest.clear_mobs(main)
	_fast(false)
	GameData.config["player_dmg_rate"] = keep_dmg
	for k in ["base_lv", "base_exp", "job_lv", "job_exp", "stat_points", "skill_points", "zeny"]:
		c.set(k, keep[k])
	c.stats = keep["stats"]
	c.inventory = keep["inventory"]
	c.quests.from_dict(keep["quests"])
	c.realms_seen = keep["realms_seen"]
	c.hp = c.max_hp()
	main.load_map(GameData.start_map())
	await SelfTest.wait_map(main, GameData.start_map())
	await SelfTest.frames(main, 5)
	# no discovery banner left for a later test (realmhide looks for one)
	if main.hud != null:
		for b in main.hud.find_children("RealmDiscovered", "", true, false):
			b.queue_free()
