extends RefCounted
## Realms (Boss 2026-10-21, scripts/realms.gd, docs/design/NEW_WORLDS_SKY_SEA.md) - selftest --only=realms, also in
## the full run:
##  data   - every map is main / sky / sea; each realm file names its town (start), its gate map (main) and Lv 50; the
##           only portals between worlds are the two gate pairs; every realm map is reached from its town without
##           leaving the realm; realm towns have the full service set + a warper that only flies inside the realm;
##           phase-1 fields: level range, 45-50 monsters, placeholder monsters flagged, no Tripo looks; Sugarplum keeps
##           Amberleaf (moved to the right edge, both ways) and Mistpine keeps Snowbell as portal 0;
##  world  - the main World Map has every main map and NO realm map (hand positions unchanged); a realm's World Map has
##           only its own maps on its own painting; the window shows the realm you stand in;
##  server - the gate refuses Base Lv 49 (message, no warp, portal cool-down), lets Lv 50 in, going home is free,
##           AUTO never routes a low hero through a gate (main routes unchanged);
##  live   - Sugarplum's sky portal and the new east gate, Nimbaria / Coralia gates are reachable on the server walk grid.

const SelfTest = preload("res://scripts/selftest.gd")
const Realms = preload("res://scripts/realms.gd")
const MapWindow = preload("res://scripts/map_window.gd")
const AutoPlay = preload("res://scripts/auto_play.gd")
const MapColliders = preload("res://scripts/server/map_colliders.gd")
const NavGrid = preload("res://scripts/server/nav_grid.gd")

const TOWN_ROLES := ["save", "bank", "heal", "tool", "weapon", "armor", "warp", "refine", "guide"]
const PHASE1 := {"sky": ["sky_cloudstep_meadows", "sky_windmill_isles", "sky_rainbow_falls"],
	"sea": ["sea_sunlit_shallows", "sea_seagrass_plains", "sea_coral_labyrinth"],
	"land_of_smile": ["smile_golden_paddies", "smile_floating_market", "smile_durian_orchard"],
	"soul_volcano": ["soul_wisp_woods", "soul_whispering_pines", "soul_moonmere"]}


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


static func run(main: Node) -> void:
	print("SELFTEST realms")
	data_tests()
	world_tests(main)
	await server_tests(main)
	nav_tests(main)
	# new-world monster sample round (Boss 2026-10-22): data + views (newmon_test.gd)
	await load("res://scripts/newmon_test.gd").run(main)


## A town with a warper of its own: realm-town warpers fly inside their realm + home to these (realm_warp_test.gd).
static func _warp_hub(mid: String) -> bool:
	for n in GameData.npcs:
		var at := str(n.get("map", ""))
		if str(n.get("kind", "")) == "warp" and (at == mid or (at == "" and mid == GameData.start_map())):
			return true
	return false


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

static func data_tests() -> void:
	var bad := PackedStringArray()
	for m in GameData.map_list:
		if not (str(m.get("realm", "main")) in ["main"] + Realms.REALMS):
			bad.append(str(m["id"]))
	check(bad.is_empty(), "every map is main / sky / sea %s" % str(bad))
	for r in Realms.REALMS:
		var d := Realms.data(r)
		var st := Realms.start(r)
		var gf := Realms.gate_from(r)
		check(not d.is_empty() and Realms.of(st) == r and MapPaintKind.town(st) and Realms.of(gf) == "main" and Realms.min_lv(r) == 50
			and str(d.get("layout", "")) == "hand" and str(d.get("name", "")) != "" and str(d.get("name_th", "")) != "",
			"%s: world file (town %s, gate %s, Lv %d, %s / %s)" % [r, st, gf, Realms.min_lv(r), str(d.get("name", "")), str(d.get("name_th", ""))])
		# the gate pair: gate map -> town and back
		var there := false
		var back := false
		for pt in GameData.map(gf).get("portals", []):
			there = there or str(pt["to_map"]) == st
		for pt in GameData.map(st).get("portals", []):
			back = back or str(pt["to_map"]) == gf
		check(there and back, "%s: gate %s <-> %s both ways" % [r, gf, st])
		# every realm map is reached from the town inside the realm
		var seen := {st: true}
		var q: Array = [st]
		while not q.is_empty():
			var cur := str(q.pop_front())
			for pt in GameData.map(cur).get("portals", []):
				var nx := str(pt["to_map"])
				if Realms.of(nx) == r and not seen.has(nx):
					seen[nx] = true
					q.append(nx)
		var lost := PackedStringArray()
		for id in Realms.maps_of(r):
			if not seen.has(id):
				lost.append(id)
		check(lost.is_empty() and Realms.maps_of(r).size() >= 4, "%s: %d maps, all reached from %s inside the realm %s" % [r, Realms.maps_of(r).size(), st, str(lost)])
		# town services
		var roles := {}
		var warp_ok := true
		for n in GameData.npcs:
			if str(n.get("map", "")) != st:
				continue
			roles[str(n.get("role", ""))] = true
			for w in n.get("warps", []):
				warp_ok = warp_ok and (Realms.of(str(w.get("map", ""))) == r or _warp_hub(str(w.get("map", "")))) and not GameData.map(str(w.get("map", ""))).is_empty()
		var miss := PackedStringArray()
		for role in TOWN_ROLES:
			if not roles.has(role):
				miss.append(role)
		check(miss.is_empty() and warp_ok, "%s: %s has save / storage / healer / shops / refiner / guide + a warper (its realm + home towns) %s" % [r, st, str(miss)])
		# phase-1 fields
		var fbad := PackedStringArray()
		var lo := 999
		var hi := 0
		for mid in PHASE1[r]:
			var m := GameData.map(mid)
			if m.is_empty() or Realms.of(mid) != r:
				fbad.append(mid + " missing")
				continue
			var lr: Array = m.get("level_range", [0, 0])
			lo = mini(lo, int(lr[0]))
			hi = maxi(hi, int(lr[1]))
			var total := 0
			for z in m.get("zones", []):
				for e in z["mobs"]:
					total += int(e["count"])
					var md: Dictionary = GameData.monsters.get(str(e["id"]), {})
					# a phase-1 placeholder or (sample round 2026-10-22, mob_dress.gd) a new-world monster of this realm
					var flagged: bool = str(md.get("placeholder", "")) != "" or str(md.get("realm", "")) == str(r)
					if md.is_empty() or str(md.get("model", "")).begins_with("tripo:") or not flagged or str(md.get("name_th", "")) == "":
						fbad.append("%s %s" % [mid, str(e["id"])])
			if total < 45 or total > 50 or int(m.get("monster_total", 0)) != total or not m.has("layout"):
				fbad.append("%s total %d" % [mid, total])
		check(fbad.is_empty() and lo == 50 and hi >= 75, "%s: phase-1 fields Lv %d-%d, 45-50 placeholder / new realm monsters each (no Tripo) %s" % [r, lo, hi, str(fbad)])
	# cross-world portals: only the gate pairs
	var cross := PackedStringArray()
	for m in GameData.map_list:
		for pt in m.get("portals", []):
			if Realms.of(str(m["id"])) != Realms.of(str(pt["to_map"])):
				cross.append("%s>%s" % [m["id"], pt["to_map"]])
	check(cross.size() == 2 * Realms.REALMS.size(), "only the gate pairs (one per realm) cross worlds %s" % str(cross))
	# Sugarplum: Amberleaf moved to the right edge, both ways
	var amb := {}
	for pt in GameData.map("sugarplum").get("portals", []):
		if str(pt["to_map"]) == "amberleaf_orchard":
			amb = pt
	var amb_back := Vector2.ZERO
	for pt in GameData.map("amberleaf_orchard").get("portals", []):
		if str(pt["to_map"]) == "sugarplum":
			amb_back = Vector2(float(pt["arrive_at"][0]), float(pt["arrive_at"][1]))
	check(not amb.is_empty() and float(amb["at"][0]) > 45.0 and absf(float(amb["at"][1])) < 1.0 and amb_back.x > 40.0,
		"Sugarplum: Amberleaf gate on the right edge %s, arrival back %s" % [str(amb.get("at", [])), str(amb_back)])
	check(str(GameData.map("mistpine_glen")["portals"][0]["to_map"]) == "snowbell", "Mistpine Glen: portal 0 still leads to Snowbell")


## MapPaint kind helper (town maps) without loading the painter.
class MapPaintKind:
	static func town(id: String) -> bool:
		return GameData.map(id).has("town")


# ---------------------------------------------------------------- world map

static func world_tests(main: Node) -> void:
	var lay := MapWindow.world_layout(Realms.MAIN)
	var pos: Dictionary = lay["pos"]
	var leak := PackedStringArray()
	var gone := PackedStringArray()
	for m in GameData.map_list:
		var id := str(m["id"])
		if Realms.of(id) != Realms.MAIN:
			if pos.has(id):
				leak.append(id)
		elif not bool(m.get("world_hidden", false)) and not pos.has(id):
			gone.append(id)
	check(leak.is_empty() and gone.is_empty(), "main World Map: every main map, no realm map (leak %s, missing %s)" % [str(leak), str(gone)])
	# hand positions of the main world are where world_map.json put them (within the label push slack)
	var wm: Dictionary = MapWindow.world_data().get("pos", {})
	var moved := PackedStringArray()
	for id in wm:
		if pos.has(id) and (pos[id] as Vector2).distance_to(Vector2(float(wm[id][0]), float(wm[id][1]))) > 0.6:
			moved.append(str(id))
	check(moved.is_empty(), "main World Map: hand positions unchanged %s" % str(moved))
	for r in Realms.REALMS:
		var rl := MapWindow.world_layout(r)
		var rp: Dictionary = rl["pos"]
		var wrong := PackedStringArray()
		for id in rp:
			if not GameData.map(str(id)).is_empty() and Realms.of(str(id)) != r:
				wrong.append(str(id))
		var have := 0
		for id in Realms.maps_of(r):
			if rp.has(id):
				have += 1
		check(wrong.is_empty() and have == Realms.maps_of(r).size() and have + (rl["planned"] as Dictionary).size() >= 21,
			"%s World Map: its %d maps + %d planned, nothing from other worlds %s" % [r, have, (rl["planned"] as Dictionary).size(), str(wrong)])
		var pw: Dictionary = MapWindow.WorldView.painted(r)
		check(bool(pw.get("ok", false)) and pw["base"] != MapWindow.WorldView.painted(Realms.MAIN).get("base"), "%s World Map: its own painting" % r)


# ---------------------------------------------------------------- server gate + AUTO

static func _wait_map(main: Node, pe, id: String, sec: float) -> bool:
	var t := 0.0
	while t < sec:
		if pe.map != null and str(pe.map.map_id) == id and not pe.traveling and str(main.map_id) == id and not main.traveling:
			return true
		await main.get_tree().process_frame
		t += main.get_process_delta_time()
	return false


static func server_tests(main: Node) -> void:
	var pe = main.me()
	var ch = pe.ch
	var keep_lv: int = ch.base_lv
	var keep_map := str(pe.map.map_id)
	var keep_pos: Vector3 = pe.global_position
	# AUTO routes: a low hero never plans through a gate; a Lv 60 one does; the main routes are unchanged
	ch.base_lv = 20
	check(AutoPlay.map_route("sugarplum", "sky_cloudstep_meadows").is_empty() and AutoPlay.map_route("snowbell", "sea_sunlit_shallows").is_empty(),
		"AUTO: no route into a realm below Lv 50")
	var main_route := AutoPlay.map_route(GameData.start_map(), "hollowroot_caverns")
	check(main_route.size() == 2 and str(main_route[1]["to_map"]) == "hollowroot_caverns", "AUTO: main-world routes unchanged")
	ch.base_lv = 60
	var r1 := AutoPlay.map_route("sugarplum", "sky_cloudstep_meadows")
	check(r1.size() == 2 and str(r1[0]["to_map"]) == "sky_nimbaria", "AUTO: Lv 60 routes Sugarplum > Nimbaria > Cloudstep")
	check(Realms.cross_block("sky_nimbaria", "sugarplum", 1) == "" and Realms.cross_block("sky_nimbaria", "sky_cloudstep_meadows", 1) == ""
		and Realms.cross_block("sugarplum", "sky_nimbaria", 49) != "" and Realms.cross_block("sugarplum", "sky_nimbaria", 50) == "",
		"gate rule: in at Lv 50, home and inside the realm always")
	# the server gate (local_server.warp)
	main.load_map("sugarplum")
	check(await _wait_map(main, pe, "sugarplum", 30.0), "to Sugarplum")
	ch.base_lv = 49
	var gate := Vector3.ZERO
	for pt in GameData.map("sugarplum")["portals"]:
		if str(pt["to_map"]) == "sky_nimbaria":
			gate = Vector3(float(pt["at"][0]), 0, float(pt["at"][1]))
	pe.portal_cd = 0.0
	main.teleport_player(gate)
	await SelfTest.frames(main, 40)
	check(str(pe.map.map_id) == "sugarplum" and not pe.traveling and pe.portal_cd > 0.0, "server: Lv 49 walks into the sky gate - refused, stays in Sugarplum")
	main.teleport_player(Vector3(0, 0, 30))
	await SelfTest.frames(main, 5)
	ch.base_lv = 50
	pe.portal_cd = 0.0
	pe.server.warp(pe, "sky_nimbaria", Vector3(0, 0, 46))
	check(await _wait_map(main, pe, "sky_nimbaria", 30.0), "server: Lv 50 enters Nimbaria")
	if str(pe.map.map_id) == "sky_nimbaria":
		# the window shows the realm you are in
		var win = main.hud.map_window
		win.open("world")
		var lay: Dictionary = win.layout()
		check(win.realm() == "sky" and lay["pos"].has("sky_nimbaria") and not lay["pos"].has(GameData.start_map()),
			"World Map in Nimbaria = Skysunpia (%d nodes)" % (lay["pos"] as Dictionary).size())
		win.close()
		# going home is always free, whatever the level
		ch.base_lv = 1
		pe.server.warp(pe, "sugarplum", Vector3(0, 0, -46))
		check(await _wait_map(main, pe, "sugarplum", 30.0), "server: back down to Sugarplum at any level")
		win.open("world")
		check(win.realm() == "main" and not win.layout()["pos"].has("sky_nimbaria"), "World Map in Sugarplum = the main world again")
		win.close()
	ch.base_lv = 60
	pe.server.warp(pe, "sea_coralia", Vector3(-46, 0, 0))
	check(await _wait_map(main, pe, "sea_coralia", 30.0), "server: Lv 60 warps into Coralia")
	ch.base_lv = keep_lv
	pe.server.warp(pe, keep_map, keep_pos)
	await _wait_map(main, pe, keep_map, 30.0)


# ---------------------------------------------------------------- walk grid

static func nav_tests(main: Node) -> void:
	var holder := Node3D.new()
	main.add_child(holder)
	for mid in ["sugarplum", "sky_nimbaria", "sea_coralia"]:
		var r := Node3D.new()
		holder.add_child(r)
		MapColliders.build(r, mid, 11, holder)
		var m: Dictionary = GameData.map(mid)
		var nav = NavGrid.build(r, float(m.get("size", 140)) / 2.0)
		var sp: Array = m.get("spawn", [0, 0])
		var spawn: Vector3 = nav.nearest_walkable(Vector3(float(sp[0]), 0, float(sp[1])))
		var bad := PackedStringArray()
		for pt in m.get("portals", []):
			var at := Vector3(float(pt["at"][0]), 0, float(pt["at"][1]))
			var goal: Vector3 = nav.nearest_walkable(at)
			var path: PackedVector3Array = nav.route(spawn, goal)
			if goal.distance_to(at) > 3.0 or (path.is_empty() and not nav.line_walkable(spawn, goal)):
				bad.append(str(pt["to_map"]))
		# where the other maps drop you here: on free ground
		for om in GameData.map_list:
			for pt in om.get("portals", []):
				if str(pt["to_map"]) == mid:
					var a := Vector3(float(pt["arrive_at"][0]), 0, float(pt["arrive_at"][1]))
					if not nav.walkable(a):
						bad.append("arrive from " + str(om["id"]))
		check(bad.is_empty(), "%s: every gate reachable from the spawn, arrivals on free ground %s" % [mid, str(bad)])
		r.free()
	holder.queue_free()
