extends RefCounted
## Built-in music per map (BGM 2026-10-21, data/bgm.json + res://audio/bgm + scripts/music.gd), selftest --only=bgm
## (also in the full run):
##  data     every map in maps.json resolves to a known theme (town + field for maps with a town), maps not in the
##           table get the kind default, every theme file exists, loads, has the length / loop points bgm.json says
##  credits  every .ogg in res://audio/bgm has exactly one credits.json "Music" line in the CC BY 4.0 form and every
##           Music line belongs to a shipped file (nothing more, nothing less)
##  player   crossfade 2-3 s between themes, the same theme on the next map keeps playing (no restart), "fade" tracks
##           crossfade at the loop seam, meadow stays on the old fallback (silence without player files), the
##           player's music folder still wins, boss uses the boss theme

const SelfTest = preload("res://scripts/selftest.gd")
const WorldBuilder = preload("res://scripts/world_builder.gd")
const MusicScript = preload("res://scripts/music.gd")
const CREDITS := "res://data/credits.json"
const LICENSE_1 := "Licensed under Creative Commons: By Attribution 4.0 License"
const LICENSE_2 := "http://creativecommons.org/licenses/by/4.0/"


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


static func run(main: Node) -> void:
	print("SELFTEST bgm")
	_data()
	_credits()
	_realms()
	await _player(main)


static func _maps() -> Array:
	var d = JSON.parse_string(FileAccess.get_file_as_string("res://data/maps.json"))
	return d["maps"] if d is Dictionary else []


static func _shipped() -> Array:
	var out := []
	var dir := str(MusicScript.bgm().get("dir", "res://audio/bgm"))
	for f in DirAccess.get_files_at(dir):
		# exported builds list "x.ogg.import" / "x.ogg.remap" next to (or instead of) the file
		var n := f.trim_suffix(".import").trim_suffix(".remap")
		if n.ends_with(".ogg") and not out.has(n):
			out.append(n)
	out.sort()
	return out


static func _data() -> void:
	var b := MusicScript.bgm()
	var themes: Dictionary = b.get("themes", {})
	check(not themes.is_empty() and b.get("maps") is Dictionary, "data/bgm.json loads (%d themes)" % themes.size())
	var bad := []
	var n := 0
	for m in _maps():
		var id := str(m.get("id", ""))
		var key := str(m.get("music", "field"))
		var ts := [MusicScript.theme_for(id, false, key)]
		if m.get("town") is Dictionary:
			ts.append(MusicScript.theme_for(id, true, str(m["town"].get("music", "town"))))
		for t in ts:
			if not themes.has(t):
				bad.append("%s:%s" % [id, t])
		n += 1
	check(n > 0 and bad.is_empty(), "every map of maps.json (%d) resolves to a known theme %s" % [n, str(bad)])
	check(MusicScript.theme_for("aldoria_meadows", true, "town") == "town_aldoria" and MusicScript.theme_for("aldoria_meadows", false, "field_2") == "meadow"
		and MusicScript.theme_for("sandglass_expanse", false, "field_gc") == "desert" and MusicScript.theme_for("crownhaven", true, "town_7") == "capital_crownhaven",
		"map table: Aldoria town / meadow, Sandglass desert, Crownhaven capital")
	# a map that is not in the table yet (new realms): default per kind
	check(MusicScript.theme_for("no_such_map", true, "town_9") == str(b["kind_default"]["town"])
		and MusicScript.theme_for("no_such_map", false, "dungeon_zz") == str(b["kind_default"]["dungeon"])
		and MusicScript.theme_for("no_such_map", false, "forest_7") == str(b["kind_default"]["forest"])
		and MusicScript.theme_for("no_such_map", false, "desert_9") == str(b["kind_default"]["desert"])
		and MusicScript.theme_for("no_such_map", false, "field_99") == str(b["kind_default"]["field"])
		and themes.has(MusicScript.theme_for("no_such_map", false, "sky_3")),
		"maps outside the table use kind_default (town / dungeon / forest / desert / field / unknown family)")
	for k in b.get("kind_default", {}):
		check(themes.has(str(b["kind_default"][k])), "kind_default %s -> %s is a theme" % [k, b["kind_default"][k]])
	var fade := float(b.get("fade", 0.0))
	check(fade >= 2.0 and fade <= 3.0 and is_equal_approx(MusicScript.FADE, fade), "crossfade between themes %.1f s (2-3 s)" % fade)
	var badf := []
	for t in themes:
		var e: Dictionary = themes[t]
		if str(e.get("file", "")) == "":
			continue
		var p := MusicScript.builtin_file(t)
		var s: AudioStreamOggVorbis = AudioStreamOggVorbis.load_from_file(p) if p != "" and FileAccess.file_exists(p) else (load(p) if p != "" else null)
		var length := s.get_length() if s else 0.0
		var ok := s != null and absf(length - float(e.get("length", 0.0))) < 1.0 and length > 60.0
		if str(e.get("loop", "")) == "fade":
			ok = ok and float(e.get("loop_start", 0.0)) < float(e.get("loop_end", 0.0)) - 30.0 and float(e.get("loop_end", 0.0)) <= length + 0.1
		elif str(e.get("loop", "")) != "native":
			ok = false
		if not ok:
			badf.append("%s(%s %.1f)" % [t, p, length])
	check(badf.is_empty(), "every built-in track loads with its length + loop points %s" % str(badf))
	check(str(themes.get("meadow", {}).get("file", "x")) == "", "meadow has no built-in track yet (old fallback)")
	check(MusicScript.builtin_file(str(b.get("boss", ""))) != "", "boss theme has a track")


## New worlds (2026-10-22): every Skysunpia / Underworld map id of world_map_<realm>.json (built or planned) has its
## realm's theme (town / fields / upper fields / dungeons / MVP), a realm map outside the table falls back to its realm's
## theme (Land of Smile / Soul Volcano prepared), a boss chase in a realm plays that realm's MVP theme, and no new-world
## track repeats a mainland title.
static func _realms() -> void:
	var b := MusicScript.bgm()
	var themes: Dictionary = b.get("themes", {})
	var maps: Dictionary = b.get("maps", {})
	var bad := []
	for r in ["sky", "sea"]:
		var wm = JSON.parse_string(FileAccess.get_file_as_string("res://data/world_map_%s.json" % r))
		var ids: Array = (wm.get("pos", {}) as Dictionary).keys() if wm is Dictionary else []
		for id in ids:
			var t := str(maps.get(id, ""))
			# Underworld keeps 3 place-specific mainland tracks (wreck / volcanic vents / bone reef)
			if not (t.begins_with(r + "_") or (r == "sea" and t in ["sunken", "volcano", "undead_fields"])) or MusicScript.builtin_file(t) == "":
				bad.append("%s:%s" % [id, t])
		if ids.size() < 21:
			bad.append("%s: %d ids" % [r, ids.size()])
	check(bad.is_empty(), "every Skysunpia / Underworld map id (built + planned) has a world theme %s" % str(bad))
	# every map of every new world in maps.json (Land of Smile / Soul Volcano too) plays a built-in track: its line in the
	# table, else its realm's town / field / dungeon theme (bgm.json "realms"), so maps added later by data alone still play
	var nbad := []
	for m in _maps():
		if str(m.get("realm", "main")) == "main":
			continue
		var t2 := str(maps.get(str(m["id"]), ""))
		if t2 == "":
			t2 = MusicScript.theme_for(str(m["id"]), m.get("town") is Dictionary, str(m.get("music", "field")))
		if t2 == "" or MusicScript.builtin_file(t2) == "":
			nbad.append("%s:%s" % [m["id"], t2])
	check(nbad.is_empty(), "every new-world map in maps.json has a built-in track (table or its realm's theme) %s" % str(nbad))
	check(MusicScript.theme_for("sky_nimbaria", true, "town") == "sky_town" and MusicScript.theme_for("sea_coralia", true, "town") == "sea_town"
		and MusicScript.theme_for("sky_cloudstep_meadows", false, "field_10") == "sky_fields" and MusicScript.theme_for("sea_sunlit_shallows", false, "field_8") == "sea_fields"
		and str(maps.get("sky_zenith_sanctum", "")) == "sky_mvp" and str(maps.get("sea_throne_of_the_deep", "")) == "sea_mvp"
		and str(maps.get("sky_stormeye_vault", "")) == "sky_dungeon" and str(maps.get("sea_kraken_maw", "")) == "sea_dungeon"
		and str(maps.get("sky_halo_cloister", "")) == "sky_high" and str(maps.get("sea_twilight_trench", "")) == "sea_deep"
		and str(maps.get("soul_wisp_woods", "")) == "soul_fields",
		"Nimbaria / Coralia towns, sky / sea fields, upper sky / the deep, dungeons, MVP maps, Soul Volcano fields")
	var rbad := []
	for r in ["sky", "sea", "land_of_smile", "soul_volcano"]:
		for fam in [[true, "town"], [false, "field_9"], [false, "dungeon_zz"]]:
			var t := MusicScript.realm_theme(r, fam[0], fam[1])
			if t == "" or MusicScript.builtin_file(t) == "":
				rbad.append("%s/%s:%s" % [r, fam[1], t])
	check(rbad.is_empty() and MusicScript.realm_theme("main", false, "field") == "" and MusicScript.realm_theme("sky", false, "dungeon_q") == "sky_dungeon",
		"realm defaults for maps outside the table (sky / sea / Land of Smile / Soul Volcano: town, field, dungeon) %s" % str(rbad))
	check(MusicScript.boss_theme("sky_cloudstep_meadows") == "sky_mvp" and MusicScript.boss_theme("sea_sunlit_shallows") == "sea_mvp"
		and MusicScript.boss_theme("sandglass_expanse") == str(b.get("boss", "")) and MusicScript.boss_theme("no_such_map") == str(b.get("boss", "")),
		"boss chase: the realm's MVP battle theme in Skysunpia / Underworld, the old boss theme on the mainland")
	var seen := {}
	var dup := []
	for t in themes:
		var ti := str(themes[t].get("title", ""))
		if ti == "":
			continue
		if seen.has(ti):
			dup.append(ti)
		seen[ti] = true
	check(dup.is_empty(), "no track title is used by two themes %s" % str(dup))


static func _credits() -> void:
	var d = JSON.parse_string(FileAccess.get_file_as_string(CREDITS))
	var lines := []
	var secs := 0
	for s in (d.get("sections", []) if d is Dictionary else []):
		if str(s.get("en", "")) == "Music":
			secs += 1
			lines = s.get("lines", [])
	check(secs == 1, "credits.json has one \"Music\" section")
	var themes: Dictionary = MusicScript.bgm().get("themes", {})
	var by_file := {}
	for t in themes:
		if str(themes[t].get("file", "")) != "":
			by_file[str(themes[t]["file"])] = str(themes[t].get("title", ""))
	var files := _shipped()
	var missing := []
	var orphan := []
	for f in files:
		if not by_file.has(f):
			orphan.append(f)
			continue
		var want := "\"%s\" Kevin MacLeod (incompetech.com)" % by_file[f]
		var hits := 0
		for ln in lines:
			var parts := str(ln).split("\n")
			if parts.size() >= 4 and parts[0] == want and parts[1] == LICENSE_1 and parts[2] == LICENSE_2 and parts[3].begins_with("ดัดแปลง:"):
				hits += 1
		if hits != 1:
			missing.append("%s=%d" % [f, hits])
	check(not files.is_empty() and orphan.is_empty(), "every file in res://audio/bgm is a bgm.json theme (%d files) %s" % [files.size(), str(orphan)])
	check(missing.is_empty(), "every shipped track has exactly one CC BY 4.0 credit line %s" % str(missing))
	var titles := []
	for f in files:
		titles.append("\"%s\" Kevin MacLeod (incompetech.com)" % by_file.get(f, "?"))
	var extra := []
	for ln in lines:
		if not titles.has(str(ln).split("\n")[0]):
			extra.append(str(ln).split("\n")[0])
	check(extra.is_empty() and lines.size() == files.size(), "no Music credit without a shipped track (%d lines, %d files) %s" % [lines.size(), files.size(), str(extra)])
	var unused := []
	for f in by_file:
		if not files.has(f):
			unused.append(f)
	check(unused.is_empty(), "every theme file of bgm.json ships %s" % str(unused))


static func _player(main: Node) -> void:
	var mu = main.music
	if mu == null:
		check(false, "music node")
		return
	var start := str(WorldBuilder.current.get("id", ""))
	var old_dir: String = mu.dir
	# the player's folder still wins (selftest folder test_music has field.ogg)
	var pf: Dictionary = mu.track_for("field_gc", "desert")
	check(old_dir == "" or mu.file_for("field_gc") == "" or str(pf["file"]) == mu.file_for("field_gc"), "player music folder wins over the built-in track (%s)" % str(pf["file"]).get_file())
	# built-in only: an empty player folder
	var empty := ProjectSettings.globalize_path("user://bgm_test_empty")
	DirAccess.make_dir_recursive_absolute(empty)
	mu.dir = empty
	mu.current_key = ""
	mu.current_theme = ""
	mu.current_file = ""
	mu.current_track = {}
	main.load_map("sandglass_expanse")
	await SelfTest.frames(main, 3)
	mu._pick_track()
	var a: int = mu._active
	var p0: AudioStreamPlayer = mu._players[a]
	check(mu.current_theme == "desert" and str(mu.current_file).ends_with("/desert.ogg") and p0.stream != null and p0.playing,
		"Sandglass Expanse plays desert.ogg (%s, %s)" % [mu.current_theme, str(mu.current_file).get_file()])
	check(not (p0.stream as AudioStreamOggVorbis).loop, "a \"fade\" track does not hard-loop (crossfade seam)")
	var s0 = p0.stream
	main.load_map("ochre_canyon")
	await SelfTest.frames(main, 3)
	mu._pick_track()
	check(mu._active == a and mu._players[a].stream == s0 and mu._players[a].playing and mu.current_theme == "desert",
		"Ochre Canyon (same theme) keeps the track playing, no restart")
	main.load_map("whisperwood_forest")
	await SelfTest.frames(main, 3)
	mu._pick_track()
	check(mu._active != a and str(mu.current_file).ends_with("/forest.ogg") and mu._fade_t < 0.5 and mu._fade_len >= 2.0 and mu._fade_len <= 3.0
		and mu._players[a].stream == s0, "Whisperwood (other theme): crossfade %.1f s from desert into forest" % mu._fade_len)
	# loop seam of a "fade" track
	var tr: Dictionary = mu.current_track
	var le := float(tr.get("loop_end", 0.0))
	check(not MusicScript.loop_due(le - 10.0, tr, 3.0) and MusicScript.loop_due(le - 2.0, tr, 3.0), "loop seam due 3 s before loop_end")
	var a2: int = mu._active
	mu.restart_loop()
	check(mu._active != a2 and mu._players[mu._active].stream == mu._players[a2].stream and mu._players[mu._active].playing and mu._fade_t == 0.0
		and is_equal_approx(mu._fade_len, 3.0), "loop seam crossfades the track into itself (3 s)")
	# meadow: no built-in track -> old fallback (empty player folder = silence)
	main.load_map("blossom_meadows")
	await SelfTest.frames(main, 3)
	mu._pick_track()
	check(mu.current_theme == "meadow" and mu.current_file == "", "Blossom Meadows (meadow) keeps the old fallback: silence without player files")
	check(mu.desired_theme("boss") == "boss" and str(mu.track_for("boss", "boss")["file"]).ends_with("/boss.ogg"), "boss chase plays the boss theme")
	# back to the start map and the player's folder
	mu.dir = old_dir
	mu.current_key = ""
	mu.current_theme = ""
	main.load_map(start if start != "" else GameData.start_map())
	await SelfTest.frames(main, 3)
	mu._pick_track()
