extends RefCounted
## Town content of the 4 new-world towns (2026-10-23) - selftest --only=realmtowns, also in the full run:
##  - each town (Nimbaria, Coralia, Ban Sabai, Lanternrest) has a quest herald with a town tour + at least one more quest,
##    and a bounty / notice board NPC (role "board", Thai name "กระดานเควส ...") with at least one quest;
##  - each tool shop sells its own local food (a "use" item with heal_hp, "realm" = the town's realm, so it is ??? until
##    the world is found);
##  - every quest of those NPCs is sound: Lv 50+, kill targets are real (non-placeholder) monsters of the same realm,
##    collect targets drop from a monster of that realm, visit places lie inside their map, and the quest name / text /
##    done text + place names have Thai (data/i18n_th.json).

const SelfTest = preload("res://scripts/selftest.gd")
const Realms = preload("res://scripts/realms.gd")

const TOWNS := {"sky_nimbaria": "cloud_puff_bun", "sea_coralia": "kelp_wrap", "smile_ban_sabai": "mango_sticky_rice",
	"soul_lanternrest": "ember_chestnuts"}


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


static func run(_main: Node) -> void:
	print("SELFTEST realmtowns")
	# guard (23/10): no monster view outside the current map root - an aborted earlier test that leaves its views in
	# the tree inflates every later monster count (towns4 / capital / zone1-5 saw +51 after newmon crashed)
	var stray := {}
	for v in _main.get_tree().get_nodes_in_group("monsters"):
		if not (_main.map_root != null and _main.map_root.is_ancestor_of(v)):
			var pn := str(v.get_parent().name) if v.get_parent() else "-"
			stray[pn] = int(stray.get(pn, 0)) + 1
	check(stray.is_empty(), "no monster view outside the current map (left by an earlier test) %s" % str(stray))
	var th = JSON.parse_string(FileAccess.get_file_as_string("res://data/i18n_th.json"))
	if not (th is Dictionary):
		th = {}
	for town in TOWNS:
		var realm := Realms.of(town)
		var herald := ""
		var board := ""
		var tool := {}
		for n in GameData.npcs:
			if str(n.get("map", "")) != town:
				continue
			match str(n.get("role", "")):
				"quest":
					herald = str(n["id"])
				"board":
					board = str(n["id"])
					check(str(n.get("name_th", "")).begins_with("กระดานเควส"), "%s: the board NPC has a Thai name that says its job" % town)
				"tool":
					tool = n
		var food: String = TOWNS[town]
		var fd: Dictionary = GameData.item(food)
		check(not fd.is_empty() and str(fd.get("type", "")) == "use" and fd.get("heal_hp") is Array and str(fd.get("realm", "")) == realm
			and food in tool.get("sells", []) and str(fd.get("name_th", "")) != "",
			"%s: the tool shop sells the local food %s (realm %s)" % [town, food, realm])
		var hq := []
		var bq := []
		for q in GameData.quest_list:
			if str(q.get("giver", "")) == herald and herald != "":
				hq.append(q)
			elif str(q.get("giver", "")) == board and board != "":
				bq.append(q)
		var tour := hq.filter(func(q): return str(q.get("type", "")) == "visit" and str(q.get("map", "")) == town)
		check(herald != "" and tour.size() == 1 and hq.size() >= 2, "%s: the herald gives a town tour + more (%d quests)" % [town, hq.size()])
		check(board != "" and bq.size() >= 1, "%s: a bounty / notice board with quests (%d)" % [town, bq.size()])
		var bad := []
		for q in hq + bq:
			var id := str(q["id"])
			var m: Dictionary = GameData.map(str(q.get("map", "")))
			if int(q.get("min_lv", 0)) < 50 or m.is_empty() or Realms.of(str(m.get("id", ""))) != realm:
				bad.append(id + ":lv/map")
			match str(q.get("type", "")):
				"kill":
					var md: Dictionary = GameData.monsters.get(str(q.get("target", "")), {})
					if md.is_empty() or md.has("placeholder") or str(md.get("realm", "")) != realm or str(q.get("target", "")).begins_with("ph_"):
						bad.append(id + ":target")
				"collect":
					var drops := false
					# item hunts (quest_log.gd roll_hunt, realm quests 2026-10-23): the quest's own drop monsters, all of this realm
					if q.has("drops") and not (q["drops"] as Dictionary).is_empty():
						drops = true
						for hm in (q["drops"] as Dictionary):
							if str(GameData.monsters.get(str(hm), {}).get("realm", "")) != realm:
								drops = false
					for mid in GameData.monsters:
						var md2: Dictionary = GameData.monsters[mid]
						if str(md2.get("realm", "")) != realm:
							continue
						for d in md2.get("drops", []):
							if str(d.get("id", "")) == str(q.get("target", "")):
								drops = true
					if not drops or GameData.item(str(q.get("target", ""))).is_empty():
						bad.append(id + ":collect")
				"visit":
					var half := float(m.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:%s" % [id, pl[0]])
				_:
					bad.append(id + ":type")
			for k in ["name", "text", "done_text"]:
				if not th.has(str(q.get(k, ""))):
					bad.append("%s:th %s" % [id, k])
		check(bad.is_empty(), "%s: every herald / board quest is sound (Lv 50+, realm maps, real targets, Thai) %s" % [town, str(bad)])
