extends RefCounted
## VIP / top-up shop (Boss 2026-10-03, data/vip.json), server side.
##  - Premium currency: Gems (เพชร) belong to the ACCOUNT (Boss 2026-10-03): online = the account record
##    (<root>/accounts/<user>/account.json "gems", server/account_store.gd; net_server.gd _open_store registers the store
##    here), single player = the local profile (user://vip_wallet.json). Every character of an account shares it.
##    CharacterState.vip (save key "vip") = {"got": one-time grants, "view": the account balance mirrored for the UI /
##    network replica, "legacy": old per-character gems not moved yet}. Old per-character "gems" are summed into the
##    account: every saved character when the server opens its store (migrate_store), else on the character's first
##    tick (single player too). REAL MONEY IS NOT IMPLEMENTED: gems only come from the admin console / chat
##    ("gems <account|character> <amount>", server/admin.gd) until a payment flow exists.
##  - VIP shop: vip.json "shop" rows {id, price (gems), vip, max_own}. Command {"t": "vip", "op": "buy", "id": item}.
##    The Hearthbell Staff is sold ONLY here (no starter gift, no NPC sale since this change).
##  - Grants: vip.json "grant" {"<account>/<character>": [item ids]} (offline: "<character>"), handed out once per
##    character on its first tick (Life.tick -> tick()); a character that already has the item is just marked.
##    Boss's tednahee keeps the staff this way. Characters that already owned the staff simply keep it.
##  - Night aura: owning the aura item (vip.json "aura".item, in the bag) shows a warm glow + light under the player
##    at night (bell_aura.gd, client side). Other players learn it from player_look "bell" (local_server.gd).

const PATH := "res://data/vip.json"
const JsonStore = preload("res://scripts/server/json_store.gd")
const MAX_GEMS := 2000000000

static var _data: Dictionary = {}
## body instance ids already checked for grants / migration this session
static var _seen: Dictionary = {}
## body instance id -> seconds until the next balance mirror
static var _sync_t: Dictionary = {}
## server/account_store.gd of the network server (net_server.gd _open_store); null = single player only
static var store = null
## single-player wallet file (tests point it elsewhere)
static var local_path := "user://vip_wallet.json"
## wallet key -> balance. Every change goes through this file, so the cache is the truth (written through at once).
static var _bal: Dictionary = {}


static func data() -> Dictionary:
	if _data.is_empty():
		var f := FileAccess.open(PATH, FileAccess.READ)
		if f != null:
			var d = JSON.parse_string(f.get_as_text())
			if d is Dictionary:
				_data = d
	return _data


static func currency_name() -> String:
	var cu: Dictionary = data().get("currency", {})
	if str(TranslationServer.get_locale()).begins_with("th"):
		return str(cu.get("name_th", "เพชร"))
	return str(cu.get("name", "Gems"))


## The shop rows (vip.json "shop").
static func shop() -> Array:
	return data().get("shop", [])


static func row(id: String) -> Dictionary:
	for r in shop():
		if r is Dictionary and str(r.get("id", "")) == id:
			return r
	return {}


static func price(id: String) -> int:
	return int(row(id).get("price", 0))


## Item that lights the night aura (the Hearthbell Staff).
static func aura_item() -> String:
	return str(data().get("aura", {}).get("item", "hearthbell_staff"))


static func aura_cfg() -> Dictionary:
	return data().get("aura", {})


## Does character `c` carry the aura item (bag)?
static func has_bell(c) -> bool:
	return c != null and int(c.count(aura_item())) > 0


# ---------------------------------------------------------------- character side

static func ensure(c) -> Dictionary:
	if not (c.vip is Dictionary):
		c.vip = {}
	var v: Dictionary = c.vip
	if not v.has("view"):
		v["view"] = 0
	if not v.has("got") or not (v["got"] is Dictionary):
		v["got"] = {}
	return v


## Save / load: only known keys, numbers clamped. Old saves: per-character "gems" -> "legacy" (moved to the account).
static func from_save(d) -> Dictionary:
	if not (d is Dictionary):
		return {"got": {}, "view": 0}
	var got := {}
	var dg = d.get("got", {})
	if dg is Dictionary:
		for k in dg:
			got[str(k)] = true
	var out := {"got": got, "view": clampi(int(d.get("view", 0)), 0, MAX_GEMS)}
	var leg := clampi(int(d.get("legacy", 0)) + int(d.get("gems", 0)), 0, MAX_GEMS)
	if leg > 0:
		out["legacy"] = leg
	return out


## Gems the character's UI shows (its account's balance, mirrored by sync()).
static func gems(c) -> int:
	if c == null or not (c.vip is Dictionary):
		return 0
	return int(c.vip.get("view", 0))


## Mirrors the account balance into the character (UI / replica); true when it changed.
static func sync(c, acct: String) -> bool:
	var v := ensure(c)
	var b := balance(acct)
	if int(v["view"]) == b:
		return false
	v["view"] = b
	c.changed.emit()
	return true


## Adds (or with n < 0 takes) gems on the character's account; returns the new balance.
static func add_gems(c, n: int, acct: String = "") -> int:
	var b := add_to(acct, n)
	sync(c, acct)
	return b


## The account of player body `pe` ("" = single player).
static func acct_of(pe) -> String:
	if pe == null:
		return ""
	var a = pe.get("account")
	return str(a) if a != null else ""


# ---------------------------------------------------------------- account wallet

static func _key(acct: String) -> String:
	if acct == "":
		return "local|" + local_path
	return "acct|%s|%s" % [str(store.root) if store != null else "", acct.to_lower()]


## Seconds an online account balance is trusted before it is read again (another channel process may have changed
## it: admin gems on Ch.1 while the player is on Ch.2). Changes themselves never trust the cache (wallet_add).
const BAL_FRESH_S := 5.0
## wallet key -> time the cached balance was read
static var _bal_t: Dictionary = {}


## Drops the cached balance of an account (a login on this channel: the wallet may have changed elsewhere).
static func forget(acct: String) -> void:
	_bal.erase(_key(acct))
	_bal_t.erase(_key(acct))


## The account's gems ("" = single player / local profile).
static func balance(acct: String) -> int:
	var k := _key(acct)
	if acct != "" and store != null and _bal.has(k) and Time.get_ticks_msec() / 1000.0 - float(_bal_t.get(k, -100.0)) > BAL_FRESH_S:
		_bal.erase(k)
	if not _bal.has(k):
		_bal_t[k] = Time.get_ticks_msec() / 1000.0
		var n := 0
		if acct == "":
			if FileAccess.file_exists(local_path):
				var d = JSON.parse_string(FileAccess.get_file_as_string(local_path))
				if d is Dictionary:
					n = int(d.get("gems", 0))
		elif store != null:
			n = int(store.account(acct.to_lower()).get("gems", 0))
		_bal[k] = clampi(n, 0, MAX_GEMS)
	return int(_bal[k])


## Sets the account's gems, written through at once (account record re-read right before: only "gems" is ours).
static func set_balance(acct: String, n: int) -> int:
	n = clampi(n, 0, MAX_GEMS)
	_bal[_key(acct)] = n
	if acct == "":
		var d := {}
		if FileAccess.file_exists(local_path):
			var old = JSON.parse_string(FileAccess.get_file_as_string(local_path))
			if old is Dictionary:
				d = old
		d["gems"] = n
		var f := FileAccess.open(local_path, FileAccess.WRITE)
		if f:
			f.store_string(JSON.stringify(d, "\t"))
	elif store != null:
		var acc: Dictionary = store.account(acct.to_lower())
		if not acc.is_empty():
			if store.has_method("wallet_add"):
				# account_store.gd save_account keeps the gems on disk (they change only through wallet_add)
				store.wallet_add(acct.to_lower(), n - int(acc.get("gems", 0)), false, MAX_GEMS)
			else:
				acc["gems"] = n
				store.save_account(acc)
	return n


static func add_to(acct: String, n: int) -> int:
	if acct != "" and store != null and store.has_method("wallet_add"):
		# transactional: re-read + change + write under the account lock (channels share account.json)
		var nb: int = store.wallet_add(acct.to_lower(), n, false, MAX_GEMS)
		if nb >= 0:
			_bal[_key(acct)] = nb
			_bal_t[_key(acct)] = Time.get_ticks_msec() / 1000.0
			return nb
	return set_balance(acct, balance(acct) + n)


## Takes `n` gems if the account has them (fresh balance, one transaction). New balance, or -1 = not enough.
static func spend(acct: String, n: int) -> int:
	if acct != "" and store != null and store.has_method("wallet_add"):
		var nb: int = store.wallet_add(acct.to_lower(), -n, true, MAX_GEMS)
		forget(acct)
		if nb >= 0:
			_bal[_key(acct)] = nb
			_bal_t[_key(acct)] = Time.get_ticks_msec() / 1000.0
		return nb
	var have := balance(acct)
	if have < n:
		return -1
	return set_balance(acct, have - n)


## Old per-character gems -> the account (once); returns the amount moved.
static func migrate(c, acct: String) -> int:
	var v := ensure(c)
	var leg := int(v.get("legacy", 0))
	if leg <= 0:
		return 0
	v.erase("legacy")
	add_to(acct, leg)
	sync(c, acct)
	c.msg("Your %d character Gems moved to your account wallet (shared by all your characters).  ·  ย้ายเพชร %d เข้าบัญชีแล้ว" % [leg, leg],
		Color(0.55, 0.85, 1.0))
	c.changed.emit()
	return leg


## Server start (net_server.gd _open_store): sums every saved character's old per-character gems into its account and
## takes them out of the character file. Returns [[user, gems], ...].
static func migrate_store(st) -> Array:
	store = st
	var out: Array = []
	if st == null:
		return out
	for u in st.all_users():
		var sum := 0
		for n in st.account(u).get("chars", []):
			var path: String = st.char_path(u, str(n))
			var d: Dictionary = JsonStore.read(path)
			var dv = d.get("vip", null)
			if dv is Dictionary and (int(dv.get("gems", 0)) > 0 or int(dv.get("legacy", 0)) > 0):
				sum += int(dv.get("gems", 0)) + int(dv.get("legacy", 0))
				dv.erase("gems")
				dv.erase("legacy")
				JsonStore.save(path, d)
		if sum > 0:
			add_to(str(u), sum)
			out.append([str(u), sum])
	return out


# ---------------------------------------------------------------- commands

## {"t": "vip", "op": "buy", "id": item}. Answer {"ok", "err"}; failures explain themselves in chat.
static func command(pe, cmd: Dictionary) -> Dictionary:
	var c = pe.ch
	ensure(c)
	var op := str(cmd.get("op", "buy"))
	var out := {"ok": false, "err": ""}
	if op == "buy":
		out = buy(c, str(cmd.get("id", "")), acct_of(pe))
	else:
		out["err"] = "Unknown VIP command."
	if not bool(out.get("ok", false)) and str(out.get("err", "")) != "":
		c.msg(str(out["err"]), Color(1, 0.6, 0.5))
	return out


static func buy(c, id: String, acct: String = "") -> Dictionary:
	var r := row(id)
	if r.is_empty() or GameData.item(id).is_empty():
		return {"ok": false, "err": "That is not sold in the VIP shop.  ·  ไม่มีสินค้านี้ในร้าน VIP"}
	var cost := int(r.get("price", 0))
	var mx := int(r.get("max_own", 0))
	if mx > 0 and int(c.count(id)) >= mx:
		return {"ok": false, "err": "You already own %s.  ·  คุณมีไอเท็มนี้แล้ว" % GameData.item_name(id)}
	# bag expansion (items.json "bag_slots"): applied at once by add_item; refused before paying when it cannot apply
	if GameData.item(id).has("bag_slots") and str(c.bag_expand_err(id)) != "":
		return {"ok": false, "err": str(c.bag_expand_err(id))}
	if cost <= 0:
		return {"ok": false, "err": "Not for sale yet.  ·  ยังไม่เปิดขาย"}
	var have := balance(acct)
	if have < cost or spend(acct, cost) < 0:
		forget(acct)
		have = balance(acct)
		sync(c, acct)
		return {"ok": false, "err": "Not enough %s (%d / %d).  ·  เพชรไม่พอ" % [currency_name(), have, cost]}
	sync(c, acct)
	c.add_item(id, 1)
	c.msg("VIP: you bought %s for %d %s.  ·  ซื้อ %s สำเร็จ" % [GameData.item_name(id), cost, currency_name(), GameData.item_name(id)],
		Color(0.55, 0.85, 1.0))
	c.notice("VIP", GameData.item_name(id))
	c.changed.emit()
	return {"ok": true, "id": id, "gems": balance(acct)}


# ---------------------------------------------------------------- grants

## The grant list of a body: "<account>/<character>" (online) or "<character>" (offline single player).
static func grants_for(account: String, char_name: String) -> Array:
	var g: Dictionary = data().get("grant", {})
	var keys := [char_name.to_lower()] if account == "" else ["%s/%s" % [account.to_lower(), char_name.to_lower()]]
	for k in g:
		if str(k).to_lower() in keys:
			return [str(k), g[k]]
	return []


## Hands out this character's grants once (owned already -> only marked). Returns the ids given now.
static func apply_grants(c, account: String) -> Array:
	var given: Array = []
	var gk: Array = grants_for(account, str(c.char_name))
	if gk.is_empty():
		return given
	var v := ensure(c)
	for id in gk[1]:
		var key := "%s:%s" % [str(gk[0]).to_lower(), str(id)]
		if bool(v["got"].get(key, false)) or GameData.item(str(id)).is_empty():
			continue
		v["got"][key] = true
		if int(c.count(str(id))) <= 0:
			c.add_item(str(id), 1)
			given.append(str(id))
			c.msg("VIP gift: %s.  ·  ได้รับของขวัญ VIP: %s" % [GameData.item_name(str(id)), GameData.item_name(str(id))], Color(0.55, 0.85, 1.0))
	c.changed.emit()
	return given


## Every physics frame per player (Life.tick): grants + old gems -> account once per body, then the account balance is
## mirrored into the character about once a second (another character of the same account may have spent / got gems).
static func tick(pe) -> void:
	if pe.ch == null:
		return
	var k: int = pe.get_instance_id()
	if not _seen.has(k):
		_seen[k] = true
		var acct := acct_of(pe)
		apply_grants(pe.ch, acct)
		migrate(pe.ch, acct)
		sync(pe.ch, acct)
		_sync_t[k] = 1.0
		return
	var t: float = float(_sync_t.get(k, 1.0)) - float(pe.get_physics_process_delta_time())
	if t <= 0.0:
		t = 1.0
		sync(pe.ch, acct_of(pe))
	_sync_t[k] = t
