extends RefCounted
## AWAKENED LOOKS (2026-10-24; Boss: the ULT awakening of every class but the tank looked like "nothing changed" - the
## same outfit + a gold aura). A class without an awakened model (<model>_awaken, only hero_dc_knight has one) now
## transforms for as long as the awakening lasts (data/awaken_looks.json, VIEW ONLY, free code-built art):
##  - one skinned mesh on the hero rig (costume_parts.gd Acc / skin / fit, builders in awaken_meshes.gd): solid
##    armour / crowns / horns (awaken_part.gdshader: hero toon ramp + ink outline) and glowing energy pieces - wings of
##    light, halos, flame rings, floating swords (awaken_glow.gdshader). Cached per class + model build + riding;
##  - a class-coloured charge on the body, the class cloth pieces (cape_parts.gd: the springy cape glows = the aura
##    cape) and the held weapon (awaken_overlay.gdshader as material_overlay; weapon = emissive blade);
##  - the golden aura (awaken_aura.gd) and the weapon trail in the class colours (player.gd).
## Everything dissolves in on the transformation flash (FADE_IN) and out when the awakening ends (FADE_OUT), on every
## view (own hero, other players, mounts, the asura ride, with or without a fashion outfit - its parts are off while
## awake, skin_look.gd parts()). Low graphics: no charge overlay, still energy (no pulse). Cost: 1 mesh instance (2
## surfaces + outline = 3 draw calls) + 1 overlay pass per body / cloth / weapon mesh, only while awakened.
## Hook: skin_look.gd parts(view) -> update(view) (called on every state change, on awaken() and when it runs out).

const CP = preload("res://scripts/costume_parts.gd")
const AM = preload("res://scripts/awaken_meshes.gd")
const PART_SH = preload("res://shaders/awaken_part.gdshader")
const OUTL_SH = preload("res://shaders/awaken_part_outline.gdshader")
const GLOW_SH = preload("res://shaders/awaken_glow.gdshader")
const CHARGE_SH = preload("res://shaders/awaken_overlay.gdshader")
const FADE_IN := 0.55
const FADE_OUT := 0.6
const TAG := "Costume_awaken"

static var _data: Dictionary = {}
static var _meshes: Dictionary = {}
## Meshes built (tests / perf).
static var built := 0
## Last decision of update() (tests).
static var last := ""


static func data() -> Dictionary:
	if _data.is_empty():
		var f := FileAccess.open("res://data/awaken_looks.json", FileAccess.READ)
		if f != null:
			var d = JSON.parse_string(f.get_as_text())
			if d is Dictionary:
				_data = d
		if _data.is_empty():
			_data = {"enabled": false, "classes": {}}
	return _data


static func enabled() -> bool:
	return bool(data().get("enabled", true))


## The awakened look of class `job` ({} = none).
static func def(job: String) -> Dictionary:
	var c = data().get("classes", {})
	if c is Dictionary and (c as Dictionary).get(job) is Dictionary:
		return c[job]
	return {}


static func classes() -> Array:
	var c = data().get("classes", {})
	return (c as Dictionary).keys() if c is Dictionary else []


static func _col(d: Dictionary, k: String, fb: String) -> Color:
	return Color(str(d.get(k, fb)))


## awaken_aura.gd colours of the class ([main, highlight]; [] = the default gold).
static func aura_colors(job: String) -> Array:
	var a: Array = def(job).get("aura", [])
	if a.size() < 2 or not enabled():
		return []
	return [Color(str(a[0])), Color(str(a[1]))]


## Weapon trail colour while awakened (alpha 0 = the normal one).
static func trail_color(job: String) -> Color:
	var d := def(job)
	if d.is_empty() or not enabled() or not d.has("trail"):
		return Color(0, 0, 0, 0)
	return Color(Color(str(d["trail"])), 0.9)


static func _low() -> bool:
	var s = Engine.get_main_loop().root.get_node_or_null("Settings") if Engine.get_main_loop() is SceneTree else null
	return s != null and str(s.get("gfx_quality")) == "low"


# ---------------------------------------------------------------- view

## Puts the awakened look on / takes it off `view` (player.gd) to match its awakened state. Cheap when nothing changed.
static func update(view) -> void:
	if view == null or not is_instance_valid(view):
		return
	var model = view.get("model")
	if not (model is Node3D) or not (model as Node).has_meta("anim"):
		return
	var awake: bool = float(view.get("_awake_t") if view.get("_awake_t") != null else 0.0) > 0.0
	var job := str(view._job()) if view.has_method("_job") else ""
	var swap: bool = view.has_method("can_awaken") and bool(view.can_awaken())
	var want := awake and enabled() and not swap and not def(job).is_empty()
	var mv = view.get("mount_view")
	var ride: bool = mv != null and is_instance_valid(mv)
	var low := _low()
	var key := "%s|%d|%d" % [job, int(ride), int(low)] if want else ""
	var cur := current(model)
	if key == "":
		if (view as Object).has_meta("awaken_look_on"):
			(view as Object).remove_meta("awaken_look_on")
		view.set("_awake_trail", Color(0, 0, 0, 0))
		if cur != null:
			last = "off %s" % job
			remove(model, true)
		return
	view.set("_awake_trail", trail_color(job))
	if cur != null and str(model.get_meta("awaken_look_key", "")) == key:
		# the weapon may have been rebuilt (equip change) while awakened: charge the new one
		_charge_weapon(model, view.get("weapon_mesh"), job, low, 1.0)
		return
	# a rebuild while already awakened (mount on / off, quality change, new model) shows at once
	var instant: bool = (view as Object).has_meta("awaken_look_on")
	var mid := str(view._hero_model_id()) if view.has_method("_hero_model_id") else ""
	var MLd = load("res://scripts/model_loader.gd")
	put(model, MLd.resolve(mid) if mid != "" else "", job, {"ride": ride, "low": low, "instant": instant,
		"weapon": view.get("weapon_mesh")})
	(view as Object).set_meta("awaken_look_on", true)
	model.set_meta("awaken_look_key", key)
	last = "on %s ride=%s low=%s instant=%s" % [job, str(ride), str(low), str(instant)]


# ---------------------------------------------------------------- model level (views, shot tools)

## The awakened look on `model` (a ModelLoader hero) of class `job`. opts: ride (bool), low (bool), instant (no fade),
## weapon (the held weapon node to charge). Returns the look's MeshInstance3D or null.
static func put(model: Node3D, model_id: String, job: String, opts: Dictionary = {}) -> MeshInstance3D:
	remove(model, false)
	var d := def(job)
	if model == null or d.is_empty():
		return null
	var sk := CP.skeleton(model)
	if sk == null:
		return null
	var f := CP.fit(model, model_id)
	if f.is_empty():
		return null
	# a look still dissolving out (awakened again right away): gone at once, its charge too
	for n in sk.get_children():
		if (n as Node).has_meta("awaken_leaving"):
			_uncharge((n as Node).get_meta("awaken_charge", []))
			(n as Node3D).visible = false
			(n as Node).queue_free()
	var ride := bool(opts.get("ride", false))
	var low := bool(opts.get("low", false))
	var mesh := mesh_for(job, f, "%s|%s" % [model_id, CP.mi0_key(model)], ride)
	if mesh == null or mesh.get_surface_count() == 0:
		return null
	var mi := MeshInstance3D.new()
	mi.name = TAG
	mi.mesh = mesh
	mi.skin = CP.skin_for(model, sk)
	# look_apply / skin dye / hy3d / costume fits leave it alone
	mi.set_meta("own_look", true)
	sk.add_child(mi)
	mi.skeleton = NodePath("..")
	mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
	var inv := CP._rel(model, sk).affine_inverse()
	mi.custom_aabb = inv * AABB(Vector3(-1.8, -0.4, -1.8), Vector3(3.6, 3.8, 3.6))
	# per view materials (the fade is per hero); shared shaders
	var mats: Array = []
	var edge := _col(d, "color4", "#ffffff")
	for s in mesh.get_surface_count():
		var m := ShaderMaterial.new()
		if mesh.surface_get_name(s) == "glow":
			m.shader = GLOW_SH
			m.set_shader_parameter("pulse", 0.0 if low else 1.0)
			m.set_shader_parameter("edge_color", edge)
		else:
			m.shader = PART_SH
			m.set_shader_parameter("edge_color", _col(d, "color", "#ffffff"))
			m.set_shader_parameter("rim_color", _col(d, "color", "#ffffff").lerp(Color.WHITE, 0.35))
			var o := ShaderMaterial.new()
			o.shader = OUTL_SH
			m.next_pass = o
			mats.append(o)
		mi.set_surface_override_material(s, m)
		mats.append(m)
	model.set_meta("awaken_look", mi)
	model.set_meta("awaken_look_mats", mats)
	# the charge (class-coloured rim / energy lines) on body, class cloth and weapon
	var charge: Array = []
	if not low:
		charge = _charge(model, sk, job, opts.get("weapon"))
	model.set_meta("awaken_charge", charge)
	mi.set_meta("awaken_charge", charge)
	var instant := bool(opts.get("instant", false))
	_set_fade(model, 1.0 if instant else 0.0)
	if not instant:
		var tw := mi.create_tween()
		tw.tween_method(func(v: float): _set_fade(model, v), 0.0, 1.0, FADE_IN).set_ease(Tween.EASE_OUT)
	return mi


static func current(model: Node3D) -> MeshInstance3D:
	if model == null or not model.has_meta("awaken_look"):
		return null
	var m = model.get_meta("awaken_look")
	return m if m != null and is_instance_valid(m) and not (m as Node).has_meta("awaken_leaving") else null


## Takes the look off (`fade` = dissolve out first). The charge overlays go with it.
static func remove(model: Node3D, fade: bool) -> void:
	if model == null or not model.has_meta("awaken_look"):
		return
	var mi = model.get_meta("awaken_look")
	var mats: Array = model.get_meta("awaken_look_mats", [])
	var charge: Array = model.get_meta("awaken_charge", [])
	for k in ["awaken_look", "awaken_look_mats", "awaken_charge", "awaken_look_key"]:
		if model.has_meta(k):
			model.remove_meta(k)
	if mi == null or not is_instance_valid(mi):
		_uncharge(charge)
		return
	if not fade or not (mi as Node).is_inside_tree():
		_uncharge(charge)
		(mi as Node3D).visible = false
		(mi as Node).queue_free()
		return
	(mi as Node).set_meta("awaken_leaving", true)
	var tw := (mi as Node).create_tween()
	tw.tween_method(func(v: float): _fade_list(mats, charge, v), 1.0, 0.0, FADE_OUT).set_ease(Tween.EASE_IN)
	tw.tween_callback(func():
		_uncharge(charge)
		if is_instance_valid(mi):
			(mi as Node).queue_free())


static func _set_fade(model: Node3D, v: float) -> void:
	if model == null or not is_instance_valid(model):
		return
	_fade_list(model.get_meta("awaken_look_mats", []), model.get_meta("awaken_charge", []), v)


static func _fade_list(mats: Array, charge: Array, v: float) -> void:
	for m in mats:
		if m is ShaderMaterial:
			(m as ShaderMaterial).set_shader_parameter("fade", v)
	for c in charge:
		var cm = (c as Array)[1] if c is Array and (c as Array).size() > 1 else null
		if cm is ShaderMaterial:
			(cm as ShaderMaterial).set_shader_parameter("strength", v)


# ---------------------------------------------------------------- charge (material_overlay)

static func _charge_mat(job: String, kind: String) -> ShaderMaterial:
	var d := def(job)
	var cfg: Dictionary = (data().get("charge", {}) as Dictionary).get(kind, {})
	var m := ShaderMaterial.new()
	m.shader = CHARGE_SH
	m.set_shader_parameter("color", _col(d, "charge", str(d.get("color", "#ffd060"))))
	m.set_shader_parameter("rim_k", float(cfg.get("rim", 0.9)))
	m.set_shader_parameter("flow_k", float(cfg.get("flow", 0.2)))
	m.set_shader_parameter("base_k", float(cfg.get("base", 0.0)))
	m.set_shader_parameter("strength", 0.0)
	return m


## [[MeshInstance3D, material], ...] the overlay went on (only meshes without an overlay of their own).
static func _charge(model: Node3D, sk: Skeleton3D, job: String, weapon) -> Array:
	var out: Array = []
	var body := _charge_mat(job, "body")
	var cloth := _charge_mat(job, "cloth")
	for n in sk.get_children():
		var m3 := n as MeshInstance3D
		if m3 == null or m3.mesh == null or str(m3.name) == TAG or m3.material_overlay != null:
			continue
		var nm := str(m3.name)
		if nm.begins_with("Costume_"):
			# fashion parts are off while awakened; anything else of that family stays as it is
			continue
		m3.material_overlay = cloth if nm.begins_with("CostumeCape_") else body
		out.append([m3, m3.material_overlay])
	_charge_weapon_into(out, weapon, job)
	return out


static func _charge_weapon_into(out: Array, weapon, job: String) -> void:
	if not (weapon is Node) or not is_instance_valid(weapon):
		return
	var wm := _charge_mat(job, "weapon")
	var nodes: Array = [weapon]
	nodes.append_array((weapon as Node).find_children("*", "MeshInstance3D", true, false))
	for n in nodes:
		var m3 := n as MeshInstance3D
		if m3 == null or m3.mesh == null or m3.material_overlay != null:
			continue
		m3.material_overlay = wm
		out.append([m3, wm])


## The held weapon changed while awakened: charge the new one (at strength `v`).
static func _charge_weapon(model: Node3D, weapon, job: String, low: bool, v: float) -> void:
	if low or not (weapon is Node) or not is_instance_valid(weapon):
		return
	var charge: Array = model.get_meta("awaken_charge", [])
	for c in charge:
		if c is Array and is_instance_valid(c[0]) and (c[0] == weapon or (weapon as Node).is_ancestor_of(c[0])):
			return
	var add: Array = []
	_charge_weapon_into(add, weapon, job)
	for c in add:
		(c[1] as ShaderMaterial).set_shader_parameter("strength", v)
	charge.append_array(add)
	model.set_meta("awaken_charge", charge)


static func _uncharge(charge: Array) -> void:
	for c in charge:
		if not (c is Array) or (c as Array).size() < 2:
			continue
		var m3 = c[0]
		if m3 != null and is_instance_valid(m3) and (m3 as MeshInstance3D).material_overlay == c[1]:
			(m3 as MeshInstance3D).material_overlay = null


# ---------------------------------------------------------------- mesh

## The merged look mesh of class `job` for this model fit (cached by class + model build + riding).
static func mesh_for(job: String, f: Dictionary, model_key: String, ride: bool) -> ArrayMesh:
	var mk := "%s|%s|%d" % [job, model_key, int(ride)]
	if _meshes.has(mk):
		return _meshes[mk]
	var d := def(job)
	var acc = CP.Acc.new()
	acc.f = f
	acc.ride = ride
	if not AM.build(str(d.get("mesh", "")), acc, d, f):
		push_warning("awaken_looks: unknown mesh " + str(d.get("mesh", "")))
	var am := ArrayMesh.new()
	for s in 2:
		if (acc.v[s] as PackedVector3Array).is_empty():
			continue
		var arr := []
		arr.resize(Mesh.ARRAY_MAX)
		arr[Mesh.ARRAY_VERTEX] = acc.v[s]
		arr[Mesh.ARRAY_NORMAL] = acc.n[s]
		arr[Mesh.ARRAY_COLOR] = acc.c[s]
		arr[Mesh.ARRAY_BONES] = acc.b[s]
		arr[Mesh.ARRAY_WEIGHTS] = acc.w[s]
		arr[Mesh.ARRAY_INDEX] = acc.i[s]
		am.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arr)
		am.surface_set_name(am.get_surface_count() - 1, "glow" if s == 1 else "solid")
	_meshes[mk] = am
	built += 1
	return am
