extends Node
## Distribution v2 (2026-10-05, distribution/README.md). FIRST autoload: in the packed build only
## ("Pandolia Online.exe" = the signed Godot exe renamed + "Pandolia Online.pck", export feature
## "pandolia_dist") it loads raw.pck (raw asset files) and the downloaded patch .pck files BEFORE any other
## autoload / script loads, so patched scripts + data are used. In the folder build (dev copy, live server,
## tests) it does nothing.
## Keep this file tiny and stable: it can never patch itself (it is loaded from the base pck).
## Patches: user://dist/<channel>/patches/*.pck, the list + order in user://dist/<channel>/state.json
## ({"base": <base build>, "patches": [names], "server": "host:port"}), written by updater.gd.

const FEATURE := "pandolia_dist"
var active := false
## Build number inside the base pck (res://build.txt before any patch) and after the patches.
var base_build := 0
var build := 0
var channel := "main"
var loaded: Array = []
var raw_ok := false
## Set when a patch in state.json was missing / failed to load (the updater repairs it).
var broken := false


func _init() -> void:
	if not OS.has_feature(FEATURE):
		return
	active = true
	channel = str(ProjectSettings.get_setting("pandolia/dist/channel", "main"))
	base_build = _read_build()
	var rp := OS.get_executable_path().get_base_dir().path_join("raw.pck")
	raw_ok = FileAccess.file_exists(rp) and ProjectSettings.load_resource_pack(rp, true)
	var st := state()
	if int(st.get("base", -1)) == base_build:
		for n in st.get("patches", []):
			var p := patch_dir().path_join(str(n))
			if FileAccess.file_exists(p) and ProjectSettings.load_resource_pack(p, true):
				loaded.append(str(n))
			else:
				broken = true
				break
	build = _read_build()
	print("DIST boot channel=%s base=%d build=%d raw=%s patches=%s" % [channel, base_build, build, raw_ok, loaded])


static func _read_build() -> int:
	if not FileAccess.file_exists("res://build.txt"):
		return 0
	return int(FileAccess.get_file_as_string("res://build.txt").strip_edges())


func dist_dir() -> String:
	return "user://dist".path_join(channel)


func patch_dir() -> String:
	return dist_dir().path_join("patches")


func state() -> Dictionary:
	var p := dist_dir().path_join("state.json")
	if not FileAccess.file_exists(p):
		return {}
	var d = JSON.parse_string(FileAccess.get_file_as_string(p))
	return d if typeof(d) == TYPE_DICTIONARY else {}


func save_state(d: Dictionary) -> bool:
	DirAccess.make_dir_recursive_absolute(dist_dir())
	var tmp := dist_dir().path_join("state.json.tmp")
	var f := FileAccess.open(tmp, FileAccess.WRITE)
	if f == null:
		return false
	f.store_string(JSON.stringify(d, "  "))
	f.close()
	return DirAccess.rename_absolute(tmp, dist_dir().path_join("state.json")) == OK


## Game server "host:port" for the lobby: from the newest patch manifest, else override.cfg; "" = none
## (folder builds). The lobby lets --join=host:port win over this.
func server_address() -> String:
	if not active:
		return ""
	var s := str(state().get("server", ""))
	if s == "":
		s = str(ProjectSettings.get_setting("pandolia/dist/server", ""))
	return s.strip_edges()
