extends RefCounted
## Roadmap feature unlocks (Boss approved roadmap v2 2026-10-04): selftest --only=roadmap.
## server/unlocks.gd registry (levels, tutorials, free pulls, tester switch, grandfathering, save round trip),
## server refusals of locked commands, the gacha gates + free pull once, the skin wells (server/skins.gd), the
## Lv 70 PK gate, and the HUD's grey locked icons. Shots: --shotroadmap=<dir> (scripts/roadmap_shot.gd).

const SelfTest = preload("res://scripts/selftest.gd")
const Unlocks = preload("res://scripts/server/unlocks.gd")
const Skins = preload("res://scripts/server/skins.gd")
const Starwell = preload("res://scripts/server/starwell.gd")
const Mounts = preload("res://scripts/server/mounts.gd")
const Pvp = preload("res://scripts/server/pvp.gd")
const CharacterState = preload("res://scripts/server/character_state.gd")

const TABLE := {"mount": 5, "life": 8, "fashion": 10, "cards": 15, "arena": 20, "homestead": 20, "weapon_skin": 25,
	"guild": 30, "awaken_preview": 40, "awaken": 40, "boss_pk": 70, "asura": 80}
const GACHAS := {"mount": "mount", "fashion": "fashion", "mount_skin": "fashion", "beast": "cards", "lantern": "homestead",
	"weapon_skin": "weapon_skin", "awaken_skin": "awaken_preview", "asura_skin": "awaken"}


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


static func _fresh(ps, n: String, lv: int):
	ps.new_character(n)
	var c = ps.ch
	c.base_lv = lv
	for s in c.job_slots:
		if s is Dictionary:
			s["base_lv"] = lv
	Mounts.ensure(c)["shards"] = 0
	return c


static func run(main: Node) -> void:
	print("SELFTEST roadmap")
	var keep := {}
	for k in ["roadmap_gates", "unlock_free_test", "awaken_free_test", "asura_free_test", "homestead_free_test"]:
		keep[k] = GameData.config.get(k, null)
	GameData.config["roadmap_gates"] = true
	GameData.config["unlock_free_test"] = false
	GameData.config["awaken_free_test"] = false
	GameData.config["asura_free_test"] = false
	GameData.config["homestead_free_test"] = false
	var ps = PlayerState
	var pe = main.me()
	pe.dead = false

	# ---- data: the approved table
	for k in TABLE:
		check(Unlocks.feature_level(k) == int(TABLE[k]), "%s opens at Lv %d" % [k, TABLE[k]])
		check(Unlocks.tutorial_of(k) != "", "%s has a tutorial id" % k)
	for g in GACHAS:
		check(Unlocks.gacha_feature(g) == str(GACHAS[g]) and int(Unlocks.gachas()[g].get("free", 0)) == 1, "gacha %s -> %s, 1 free pull" % [g, GACHAS[g]])
	check(str(Unlocks.gachas()["awaken_skin"].get("use", "")) == "awaken" and str(Unlocks.gachas()["asura_skin"].get("use", "")) == "asura", "awaken skins wear after the Awakening Trial (Lv 40), asura skins at 80")
	var all_by_50 := true
	for g in GACHAS:
		if Unlocks.feature_level(str(GACHAS[g])) > 50:
			all_by_50 = false
	check(all_by_50, "every gacha is open by Lv 50 (Boss rule)")
	check(Unlocks.key_of("fishing") == "life" and Unlocks.key_of("starwell") == "mount" and Unlocks.key_of("guild_war") == "boss_pk", "aliases")

	# ---- Lv 1: everything locked, the reasons say the level
	var c = _fresh(ps, "Roadie", 1)
	for k in TABLE:
		check(not Unlocks.feature_ok(c, k), "Lv 1: %s locked" % k)
	check(Unlocks.feature_why(c, "mount", true).contains("ปลดล็อกที่ Lv 5"), "Thai reason: %s" % Unlocks.feature_why(c, "mount", true))
	check(Unlocks.feature_why(c, "mount", false).contains("Lv 5"), "English reason: %s" % Unlocks.feature_why(c, "mount", false))
	check(Unlocks.lock_label(c, "guild", true) == "ปลดล็อกที่ Lv 30", "grey button label: %s" % Unlocks.lock_label(c, "guild", true))
	check(not Unlocks.complete_tutorial(c, "mount") and not Unlocks.tutorial_done(c, "mount"), "tutorial refused below its level")
	# server refusals
	var r: Dictionary = main.send({"t": "mount", "on": true})
	check(not bool(r.get("ok", true)) and bool(r.get("locked", false)), "ride refused at Lv 1")
	r = main.send({"t": "mount", "on": false})
	check(bool(r.get("ok", false)), "getting off is never blocked")
	r = main.send({"t": "star_pull", "well": "mount", "n": 1})
	check(not bool(r.get("ok", true)), "Starwell refused at Lv 1")
	r = main.send({"t": "star_pull", "well": "fashion", "n": 1})
	check(not bool(r.get("ok", true)), "Fashion gacha refused at Lv 1")
	r = main.send({"t": "fish_cast"})
	check(not bool(r.get("ok", true)) and bool(r.get("locked", false)), "fishing refused at Lv 1")
	r = main.send({"t": "cook", "recipe": "x"})
	check(bool(r.get("locked", false)), "cooking refused at Lv 1")
	r = main.send({"t": "cst", "op": "auto"})
	check(bool(r.get("locked", false)), "Beast Constellation refused at Lv 1")
	r = main.send({"t": "arena_join"})
	check(bool(r.get("locked", false)), "arena refused at Lv 1")
	r = main.send({"t": "guild_create", "name": "Roadies"})
	check(bool(r.get("locked", false)), "guild create refused at Lv 1")
	r = main.send({"t": "pk_mode", "mode": "free"})
	check(bool(r.get("locked", false)), "Free PK refused before Lv 70")
	r = main.send({"t": "pk_mode", "mode": "peace"})
	check(not bool(r.get("locked", false)), "Peace mode is never blocked")
	r = main.send({"t": "gw_join"})
	check(bool(r.get("locked", false)), "guild war refused before Lv 70")
	r = main.send({"t": "house_list"})
	check(bool(r.get("locked", false)), "homestead refused at Lv 1")
	r = main.send({"t": "lantern_pull", "banner": "x", "n": 1})
	check(bool(r.get("locked", false)), "Wishing Lantern refused at Lv 1")
	r = main.send({"t": "tut_done", "key": "mount"})
	check(not bool(r.get("ok", true)), "tut_done refused below the level")

	# ---- Lv 5: the mount tutorial, the free pull exactly once
	c.base_lv = 5
	for s in c.job_slots:
		if s is Dictionary:
			s["base_lv"] = 5
	check(not Unlocks.feature_ok(c, "mount") and Unlocks.tutorial_ready(c, "mount"), "Lv 5: mount waits for its tutorial")
	check(Unlocks.pending_tutorials(c) == ["mount"], "pending tutorials at Lv 5: %s" % str(Unlocks.pending_tutorials(c)))
	var seen: Array = []
	var cb := func(k): seen.append(k)
	c.leveled.connect(cb)
	r = main.send({"t": "tut_done", "key": "mount"})
	c.leveled.disconnect(cb)
	check(bool(r.get("ok", false)) and Unlocks.feature_ok(c, "mount"), "tut_done at Lv 5 opens mounts")
	check("unlock" in seen, "the unlock hook fired (leveled 'unlock')")
	check(not Unlocks.complete_tutorial(c, "mount"), "complete_tutorial is idempotent")
	check(not Mounts.owned(c).is_empty(), "the first free mount is owned")
	check(Unlocks.free_pulls(c, "mount") == 1, "1 free Starwell pull")
	Mounts.ensure(c)["shards"] = 0
	r = main.send({"t": "star_pull", "well": "mount", "n": 1})
	check(bool(r.get("ok", false)) and bool(r.get("free", false)) and (r.get("results", []) as Array).size() == 1, "free pull works with 0 shards")
	check(Unlocks.free_pulls(c, "mount") == 0, "free pull used up")
	r = main.send({"t": "star_pull", "well": "mount", "n": 1})
	check(not bool(r.get("ok", true)), "second pull needs shards again")
	r = main.send({"t": "mount", "on": true})
	check(bool(r.get("ok", false)), "riding works after the tutorial")
	main.send({"t": "mount", "on": false})
	r = main.send({"t": "tut_done", "key": "awaken"})
	check(not bool(r.get("ok", true)), "quest-only features cannot be skipped by tut_done")

	# ---- Lv 10: fashion (free outfit + 2 free pulls), skins wells
	c.base_lv = 10
	for s in c.job_slots:
		if s is Dictionary:
			s["base_lv"] = 10
	check(Unlocks.complete_tutorial(c, "fashion") and Unlocks.feature_ok(c, "fashion"), "fashion tutorial at Lv 10")
	check(Skins.owns(c, str(Skins.data().get("free_outfit", ""))) and Skins.worn(c, "fashion") == str(Skins.data().get("free_outfit", "")), "the free outfit is owned + worn")
	check(Unlocks.free_pulls(c, "fashion") == 1 and Unlocks.free_pulls(c, "mount_skin") == 1, "1 free pull each: fashion + mount skins")
	Starwell.rng_override = RandomNumberGenerator.new()
	Starwell.rng_override.seed = 4242
	r = main.send({"t": "star_pull", "well": "mount_skin", "n": 1})
	var got := str((r.get("results", [{}]) as Array)[0].get("id", "")) if not (r.get("results", []) as Array).is_empty() else ""
	check(bool(r.get("ok", false)) and Skins.owns(c, got) and Skins.kind_of(got) == "mount_skin", "mount skin pulled: %s" % got)
	check(Skins.worn(c, "mount_skin") == got and Skins.look(c).get("mount_skin", "") == got, "first skin is worn + seen by others")
	r = main.send({"t": "wardrobe", "op": "wear", "kind": "mount_skin", "id": ""})
	check(bool(r.get("ok", false)) and Skins.worn(c, "mount_skin") == "", "take a skin off")
	r = main.send({"t": "wardrobe", "op": "wear", "kind": "fashion", "id": "fs_starlight"})
	check(not bool(r.get("ok", true)), "cannot wear a skin you do not own")
	Mounts.ensure(c)["shards"] = 100
	r = main.send({"t": "star_pull", "well": "fashion", "n": 10})
	check(bool(r.get("ok", false)) and (r.get("results", []) as Array).size() == 10 and Mounts.shards(c) < 100, "fashion x10 pays 100 shards")
	var epic := false
	for e in r.get("results", []):
		if Mounts.rarity_rank(str(e.get("rarity", ""))) >= Mounts.rarity_rank("epic"):
			epic = true
	check(epic, "x10 holds an Epic or better (pity)")
	check(Unlocks.free_pulls(c, "fashion") == 1, "a x10 does not eat the free single pull")
	var odds := Starwell.odds("weapon_skin")
	var tot := 0.0
	for o in odds:
		tot += float(o["pct"])
	check(absf(tot - 100.0) < 0.01 and odds.size() == Skins.pool("weapon_skin", "common").size() + Skins.pool("weapon_skin", "rare").size() + Skins.pool("weapon_skin", "epic").size() + Skins.pool("weapon_skin", "mythic").size(), "weapon skin rates add up to 100 %%")
	Starwell.rng_override = null

	# ---- Lv 40: awaken skins pull, but wear only after the Awakening
	c.base_lv = 40
	for s in c.job_slots:
		if s is Dictionary:
			s["base_lv"] = 40
	check(Unlocks.complete_tutorial(c, "awaken_preview") and Unlocks.gacha_ok(c, "awaken_skin"), "Lv 40: awaken skin gacha open")
	r = main.send({"t": "star_pull", "well": "awaken_skin", "n": 1})
	var aw := str((r.get("results", [{}]) as Array)[0].get("id", "")) if not (r.get("results", []) as Array).is_empty() else ""
	check(bool(r.get("ok", false)) and Skins.owns(c, aw), "awaken skin pulled (free): %s" % aw)
	check(Skins.shown(c, "awaken_skin") == "" and not Unlocks.gacha_use_ok(c, "awaken_skin"), "not shown before the Awakening")
	r = main.send({"t": "wardrobe", "op": "wear", "kind": "awaken_skin", "id": aw})
	check(not bool(r.get("ok", true)) and str(r.get("error", "")).contains("40"), "wear refused until the Awakening Trial: %s" % str(r.get("error", "")))
	check(not Unlocks.gacha_ok(c, "asura_skin"), "asura skin gacha still locked at 40")

	# ---- tester switch
	GameData.config["unlock_free_test"] = true
	var lo = CharacterState.new()
	lo.new_character("Tiny")
	var all_open := true
	for k in TABLE:
		if not Unlocks.feature_ok(lo, k):
			all_open = false
	check(all_open and Unlocks.awaken_ok(lo) and Unlocks.asura_ok(lo), "tester switch: everything open at Lv 1")
	GameData.config["unlock_free_test"] = false
	GameData.config["roadmap_gates"] = false
	check(Unlocks.feature_ok(lo, "mount") and not Unlocks.awaken_ok(lo), "gates off: new gates open, Awakening keeps its quest")
	GameData.config["roadmap_gates"] = true

	# ---- grandfathering: an old save (no "unlocks") keeps what its level / use earned
	var old = CharacterState.new()
	old.new_character("Veteran")
	old.base_lv = 35
	for s in old.job_slots:
		if s is Dictionary:
			s["base_lv"] = 35
	var d: Dictionary = old.to_dict()
	d.erase("unlocks")
	var back = CharacterState.new()
	back.from_dict(d)
	var gf_ok := true
	for k in ["mount", "life", "fashion", "cards", "arena", "homestead", "weapon_skin", "guild"]:
		if not Unlocks.feature_ok(back, k):
			gf_ok = false
	check(gf_ok, "Lv 35 old save: every feature up to Lv 30 stays open")
	check(not Unlocks.feature_ok(back, "awaken_preview") and not Unlocks.awaken_ok(back), "Lv 35 old save: Lv 40 / 50 still locked")
	check(Unlocks.free_pulls(back, "mount") == 1 and Unlocks.free_pulls(back, "weapon_skin") == 1, "grandfathered features get their free pulls")
	var young = CharacterState.new()
	young.new_character("Homebody")
	young.base_lv = 12
	young.quests.done.append("life_home_1")
	young.guild = "7"
	var d2: Dictionary = young.to_dict()
	d2.erase("unlocks")
	var back2 = CharacterState.new()
	back2.from_dict(d2)
	check(Unlocks.feature_ok(back2, "homestead"), "Lv 12 old save with a house keeps the homestead (used = grandfathered) %s" % str(back2.unlocks))
	check(Unlocks.feature_ok(back2, "guild"), "Lv 12 old save in a guild keeps guilds (guild '%s')" % str(back2.guild))
	check(not Unlocks.feature_ok(back2, "cards"), "Lv 12 old save: cards (Lv 15) locked")
	# save round trip: the roadmap state + wardrobe survive, no second grandfather pass
	var d3: Dictionary = c.to_dict()
	var c3 = CharacterState.new()
	c3.from_dict(JSON.parse_string(JSON.stringify(d3)))
	check(Unlocks.feature_ok(c3, "fashion") and Unlocks.feature_ok(c3, "awaken_preview") and Unlocks.free_pulls(c3, "fashion") == 1, "save round trip keeps tutorials + free pulls")
	check(Skins.owns(c3, aw) and Skins.worn(c3, "fashion") == Skins.worn(c, "fashion"), "save round trip keeps the wardrobe")
	var fresh = CharacterState.new()
	fresh.new_character("Newbie")
	fresh.base_lv = 60
	var d4: Dictionary = JSON.parse_string(JSON.stringify(fresh.to_dict()))
	var c4 = CharacterState.new()
	c4.from_dict(d4)
	check(not Unlocks.feature_ok(c4, "mount"), "a roadmap-era save is not grandfathered again")

	# ---- per-class level: a low alt class keeps the character's features
	var alt = CharacterState.new()
	alt.new_character("Alty")
	alt.base_lv = 6
	alt.job_slots = [{"job": "defend_counter", "base_lv": 33}, {"job": "magic_control", "base_lv": 6}]
	Unlocks.complete_tutorial(alt, "guild", true)
	check(Unlocks.level_for(alt, "guild") == 33 and Unlocks.feature_ok(alt, "guild"), "char level = best class (33) for guild")
	check(Unlocks.level_for(alt, "awaken") == 6, "Awakening reads the active class")

	# ---- Lv 70 PK
	var srv = main.server
	var pb_c := CharacterState.new()
	pb_c.new_character("Rival")
	pb_c.base_lv = 75
	var pb = srv.add_player(pb_c, true, 98)
	srv.enter_map(pb, pe.map.map_id, pe.global_position + Vector3(2, 0, 0))
	await SelfTest.frames(main, 3)
	c.base_lv = 75
	for s in c.job_slots:
		if s is Dictionary:
			s["base_lv"] = 75
	check(not Pvp.field_ok(srv, pe, pb), "no field PK without the boss_pk feature")
	Unlocks.complete_tutorial(c, "boss_pk")
	check(Unlocks.feature_ok(c, "boss_pk"), "boss-area PK open at 75 after its tutorial")
	check(not Pvp.field_ok(srv, pe, pb), "PK needs the feature on both sides")
	srv.remove_player(pb)

	# ---- Awakening / Asura Rider wrappers unchanged
	# Boss 2026-10-09: Awakening at Lv 40 (merged into the ULT)
	c.base_lv = 40
	check(not Unlocks.awaken_ok(c) and Unlocks.feature_why(c, "awaken").contains("40"), "Awakening still needs its trial at 40")
	c.quests.done.append("awaken_trial")
	check(Unlocks.awaken_ok(c) and Unlocks.feature_ok(c, "awaken"), "trial done -> Awakening open (wrapper + registry agree)")

	# ---- QA100: skin_look dye - the dyed copy lives on the mesh node (no global cache that kept every view's
	# materials: +48 MB per spawned fashion view), the original material_override comes back when the skin is off
	var SL = load("res://scripts/skin_look.gd")
	var droot := Node3D.new()
	var dmi := MeshInstance3D.new()
	dmi.mesh = BoxMesh.new()
	var tmat := ShaderMaterial.new()
	tmat.shader = load("res://shaders/toon.gdshader")
	dmi.material_override = tmat
	droot.add_child(dmi)
	var fsdye: Array = []
	for fid in Skins.of_kind("fashion"):
		if (Skins.def(str(fid)).get("dye", []) as Array).size() >= 4:
			fsdye = Skins.def(str(fid)).get("dye", [])
			break
	SL.dye(droot, fsdye, [])
	var dyed1 = dmi.material_override
	SL.dye(droot, fsdye, [])
	var dyed2 = dmi.material_override
	SL.dye(droot, [], [])
	check(dyed1 != tmat and dyed1 == dyed2 and dmi.has_meta("skin_dye_o") and dmi.material_override == tmat and not ("_dyed" in (SL as GDScript).get_script_constant_map())
		and SL.get("_dyed") == null, "skin dye: copy kept on the mesh (reused), override restored when the skin is off, no global cache")
	droot.free()

	# ---- HUD: grey locked menu icons (ui/hud_menu.gd)
	await _hud_checks(main, ps)

	for k in keep:
		if keep[k] == null:
			GameData.config.erase(k)
		else:
			GameData.config[k] = keep[k]


static func _hud_checks(main: Node, ps) -> void:
	var hud = main.hud
	var menu = hud.get_node_or_null("UI/MenuIcons") if hud else null
	if menu == null and hud:
		for n in hud.find_children("MenuIcons", "", true, false):
			menu = n
	if menu == null or not menu.has_method("locked_key"):
		check(false, "HUD menu has locked icons (MenuIcons.locked_key)")
		return
	_fresh(ps, "Greybox", 3)
	await SelfTest.frames(main, 2)
	check(menu.locked_key("stable") == "mount" and menu.locked_key("well") == "mount" and menu.locked_key("guild") == "guild", "menu icons map to features")
	check(menu.is_locked("stable") and menu.is_locked("guild") and not menu.is_locked("bag"), "Lv 3: Mounts / Guild grey, Bag open")
	var tip: String = menu.lock_tip("guild")
	check(tip.contains("30"), "locked icon tip: %s" % tip)
	menu.run("_guild")
	check(true, "clicking a locked icon does not crash")
	ps.ch.base_lv = 30
	for s in ps.ch.job_slots:
		if s is Dictionary:
			s["base_lv"] = 30
	Unlocks.complete_tutorial(ps.ch, "guild")
	check(not menu.is_locked("guild"), "after the guild tutorial the icon is open")
	# wardrobe window (ui/wardrobe_ui.gd): grey tabs, free pull button, pull reveal, wear
	var c = ps.ch
	Unlocks.complete_tutorial(c, "fashion")
	check(not menu.is_locked("wardrobe"), "Wardrobe icon open after the fashion tutorial")
	var W = load("res://scripts/ui/wardrobe_ui.gd").inst(hud)
	W.open("fashion")
	await SelfTest.frames(main, 2)
	var body: Control = hud.bodies["wardrobe"]
	var tab_aw: Button = body.find_child("Tab_awaken_skin", true, false)
	check(tab_aw != null and tab_aw.text.contains("Lv 40"), "awaken skins tab grey: %s" % (tab_aw.text if tab_aw else "-"))
	var b1: Button = body.find_child("Pull1", true, false)
	check(b1 != null and not b1.disabled, "x1 button enabled with the free pull (0 shards)")
	var grid: Control = body.find_child("WardrobeGrid", true, false)
	check(grid != null and grid.get_child_count() == Skins.of_kind("fashion").size(), "collection shows every fashion skin (%d)" % (grid.get_child_count() if grid else -1))
	Mounts.ensure(c)["shards"] = 0
	W._pull(1)
	await SelfTest.frames(main, 2)
	check(W.reveal != null and is_instance_valid(W.reveal) and Unlocks.free_pulls(c, "fashion") == 0, "free pull from the window -> reveal")
	W.close_reveal()
	c.base_lv = 12
	for s2 in c.job_slots:
		if s2 is Dictionary:
			s2["base_lv"] = 12
	W.kind = "weapon_skin"
	W.fill()
	var lw: Control = hud.bodies["wardrobe"].find_child("LockWhy", true, false)
	check(lw != null and (lw as Label).text.contains("25"), "weapon skins page explains Lv 25")
	W.toggle()
