extends RefCounted
## Client crash / hang reports (crash_watch.gd, net/crash_report.gd, net_server.gd "crash_report" / "bye"):
## selftest --only=crashreport (also in the full run).
##  1. units: sanitizing (passwords, tokens, IPs, e-mails, user folders), log tail, file names, rate limits
##  2. a session is "killed" (marker + ring left behind, a fake rotated Godot log of it) -> the relaunch makes a
##     sanitized "crash" report from the marker, the ring buffer and the right log
##  3. a real test server + client over ENet on 127.0.0.1 (own multiplayer branches in this process): after login
##     the pending report is sent, stored as reports/crash/<date>/<user>_<char>_<time>.json, logged
##     "CRASHREPORT user/char crash" and acknowledged (pending copy deleted)
##  4. a hang: the main loop stalls -> the watchdog thread records it with the AUTO state -> sent on recovery
##  5. script errors (rate-limited batch) + memory samples in the ring
##  6. disconnect reasons in the server log: bye (quit), closed without bye (drop), silence (timeout)

const SelfTest = preload("res://scripts/selftest.gd")
const CrashWatch = preload("res://scripts/crash_watch.gd")
const CrashReport = preload("res://scripts/net/crash_report.gd")
const ServerLog = preload("res://scripts/server/server_log.gd")
const CharacterState = preload("res://scripts/server/character_state.gd")

const ROOT := "user://crashreport_test"
const USER := "crtest"
const PW := "crpass1"
const CHAR := "Crashy"


static func check(ok: bool, what: String) -> void:
	SelfTest.check(ok, "crashreport: " + what)


static func frames(main: Node, n: int) -> void:
	await SelfTest.frames(main, n)


## Waits up to n physics frames for cond; true when it held.
static func wait_for(main: Node, cond: Callable, n: int) -> bool:
	for i in n:
		if cond.call():
			return true
		await main.get_tree().physics_frame
	return cond.call()


static func run(main: Node) -> void:
	print("SELFTEST crashreport")
	_rm_tree(ROOT)
	DirAccess.make_dir_recursive_absolute(ROOT)
	unit_tests()
	var w2 = await relaunch_tests(main)
	if w2 == null:
		return
	await server_tests(main, w2)


static func unit_tests() -> void:
	var raw := "login tester --pass=hunter2 from 203.0.113.7:24640 pw=abc123 token: xyzTOKEN99 password=\"p@ss w\" mail a.b@example.com " + \
		"C:\\Users\\somchai\\AppData\\Roaming\\Godot https://discord.com/api/webhooks/1/abc?wait=true Authorization: Bearer abcdefghijklmnop " + \
		"[::ffff:10.0.0.5] fe80::1:2:3:4 at 2026-10-17 15:00:50 Lv 58 v4.7.2.stable"
	var s := CrashReport.sanitize(raw)
	var leaked := []
	for bad in ["hunter2", "203.0.113.7", "abc123", "xyzTOKEN99", "p@ss", "a.b@example.com", "somchai", "wait=true", "abcdefghijklmnop", "10.0.0.5", "fe80::1:2:3:4"]:
		if s.contains(bad):
			leaked.append(bad)
	check(leaked.is_empty(), "sanitize masks passwords, tokens, IPs, e-mails, user folders, URL queries (leaked %s)" % str(leaked))
	check(s.contains("2026-10-17 15:00:50") and s.contains("Lv 58") and s.contains("v4.7.2.stable") and s.contains("C:\\Users\\<user>"),
		"sanitize keeps times, levels, versions (%s)" % s.right(90))
	var nested = CrashReport.sanitize_value({"log": {"tail": "ip 192.168.1.6"}, "list": ["--pass=zz9"], "n": 3})
	check(not JSON.stringify(nested).contains("192.168.1.6") and not JSON.stringify(nested).contains("zz9") and int(nested["n"]) == 3,
		"sanitize_value walks dictionaries / arrays")
	var lines: Array = []
	for i in 500:
		lines.append("line %d" % i)
	var tail := CrashReport.tail_text("\n".join(lines))
	check(tail.begins_with("line 200") and tail.ends_with("line 499"), "log tail = the last %d lines" % CrashReport.LOG_LINES)
	check(CrashReport.tail_text("x".repeat(100000)).length() <= CrashReport.LOG_BYTES + 20, "log tail is size-capped")
	check(CrashReport.file_part("Ted/../..\\x y") == "Tedx_y" and CrashReport.file_part("ทีด") == "ทีด", "file names: no path characters, Thai kept (%s)" % CrashReport.file_part("Ted/../..\\x y"))
	var st := {}
	var errs: Array = []
	for i in CrashReport.RATE_MAX + 1:
		errs.append(CrashReport.rate_check(st, "u1", 1000.0 + i))
	check(errs.slice(0, CrashReport.RATE_MAX).all(func(e): return e == "") and str(errs[-1]).begins_with("rate limit")
		and CrashReport.rate_check(st, "u2", 1010.0) == "" and CrashReport.rate_check(st, "u1", 1000.0 + CrashReport.RATE_WINDOW + 10.0) == "",
		"rate limit per account: %d per %d min, other accounts unaffected, window slides" % [CrashReport.RATE_MAX, int(CrashReport.RATE_WINDOW / 60.0)])
	var sd := {}
	var day_ok := true
	for i in CrashReport.DAY_MAX:
		day_ok = day_ok and CrashReport.rate_check(sd, "u3", 1000.0 + i * CrashReport.RATE_WINDOW) == ""
	check(day_ok and CrashReport.rate_check(sd, "u3", 1000.0 + CrashReport.DAY_MAX * CrashReport.RATE_WINDOW).begins_with("daily"), "daily cap per account (%d)" % CrashReport.DAY_MAX)
	var big := {"reason": "crash", "log": {"tail": "x".repeat(CrashReport.SERVER_MAX_BYTES + 10)}}
	check(not bool(CrashReport.store(ROOT + "/units", "u", "c", big).get("ok", true)), "the server refuses an oversized report")
	check(not CrashWatch.should_run(), "the watch is off in headless runs / tests (only the test's own instances run)")


## A session is killed, the next start turns its marker into a report. Returns the second watch (still running).
static func relaunch_tests(main: Node):
	var cdir := ROOT + "/client"
	var ldir := ROOT + "/logs"
	DirAccess.make_dir_recursive_absolute(ldir)
	var w1 = CrashWatch.new()
	w1.name = "CrashWatchTest1"
	w1.log_path = ldir.path_join("godot.log")
	w1.main_node = main
	main.add_child(w1)
	w1.start(cdir)
	check(w1.enabled and FileAccess.file_exists(cdir + "/session.json"), "a 'session running' marker is written at start")
	await frames(main, 3)
	w1.note("test", {"what": "before the kill"})
	push_error("crashreport test: deliberate error password=hunter2 - ignore this line")
	await frames(main, 3)
	w1.sample_memory()
	w1.flush()
	var ring = JSON.parse_string(FileAccess.get_file_as_string(cdir + "/ring.json"))
	var err_ev: Array = (ring.get("ring", []) as Array).filter(func(e): return str(e.get("k", "")) == "error") if ring is Dictionary else []
	check(not err_ev.is_empty() and str(err_ev[-1]["msg"]).contains("deliberate error") and not str(err_ev[-1]["msg"]).contains("hunter2"),
		"push_error reaches the ring buffer through the Logger, sanitized (%s)" % (str(err_ev[-1]["msg"]).left(80) if not err_ev.is_empty() else "none"))
	check(ring is Dictionary and (ring.get("mem", []) as Array).size() >= 1 and (ring["ring"] as Array).any(func(e): return str(e.get("k", "")) == "mem"),
		"memory samples go to the memory series + the ring")
	var sid1: String = w1.session_id
	# the Godot log of that session: Godot copies godot.log to godot<time>.log at the next start
	var body := PackedStringArray(["Godot Engine v4.7.2.stable", "CRASHWATCH session %s build 0" % sid1])
	for i in 400:
		body.append("frame %d hp ok" % i)
	body.append("NET login tester --pass=hunter2 to 203.0.113.7 token=abcdef C:\\Users\\somchai\\x")
	body.append("LAST LINE BEFORE THE CRASH")
	_write(ldir.path_join("godot2026-10-17T01.00.00.log"), "\n".join(body))
	_write(ldir.path_join("godot2026-10-17T02.00.00.log"), "Godot Engine\nCRASHWATCH session someoneelse build 0\nOTHER SESSION\n")
	w1.simulate_kill()
	main.remove_child(w1)
	w1.free()
	check(FileAccess.file_exists(cdir + "/session.json"), "a killed session leaves its marker behind")
	# relaunch
	var w2 = CrashWatch.new()
	w2.name = "CrashWatchTest2"
	w2.log_path = ldir.path_join("godot.log")
	w2.main_node = main
	main.add_child(w2)
	w2.start(cdir)
	# (the killed session's error batch waits in pending too: it goes out with the crash report)
	var pend: Array = w2.pending_files().filter(func(f): return str(f).get_file().begins_with("crash_"))
	check(pend.size() == 1 and w2.last_crash_file == str(pend[0]), "the relaunch turns the left marker into one crash report (%s)" % str(w2.pending_files()))
	if pend.is_empty():
		w2.stop(true)
		main.remove_child(w2)
		w2.free()
		return null
	var txt := FileAccess.get_file_as_string(pend[0])
	var rep = JSON.parse_string(txt)
	check(rep is Dictionary and str(rep.get("reason", "")) == "crash" and str(rep.get("session", "")) == sid1, "the report names the crashed session")
	var lg: Dictionary = rep.get("log", {})
	check(bool(lg.get("matched", false)) and str(lg.get("file", "")) == "godot2026-10-17T01.00.00.log" and str(lg.get("tail", "")).ends_with("LAST LINE BEFORE THE CRASH")
		and str(lg.get("tail", "")).split("\n").size() <= CrashReport.LOG_LINES,
		"the log tail comes from that session's rotated log, not the newest one (%s, %d lines)" % [str(lg.get("file", "")), str(lg.get("tail", "")).split("\n").size()])
	var leaks := []
	for bad in ["hunter2", "203.0.113.7", "abcdef", "somchai"]:
		if txt.contains(bad):
			leaks.append(bad)
	check(leaks.is_empty(), "nothing secret in the report file (leaked %s)" % str(leaks))
	var rr: Array = rep.get("ring", [])
	check(rr.any(func(e): return str(e.get("k", "")) == "test") and rr.any(func(e): return str(e.get("k", "")) == "error"),
		"the ring buffer of the killed session is in the report (%d events)" % rr.size())
	check(rep.has("build") and rep.has("os") and rep.has("gpu") and rep.has("engine") and rep.has("cpu"), "build, OS, CPU and GPU are in the report")
	var m2 = JSON.parse_string(FileAccess.get_file_as_string(cdir + "/session.json"))
	check(m2 is Dictionary and str(m2.get("id", "")) == w2.session_id and w2.session_id != sid1, "the new session has its own marker")
	return w2


## A test server + a client over ENet (127.0.0.1): reports arrive, hangs, errors, disconnect reasons.
static func server_tests(main: Node, w2) -> void:
	var tree: SceneTree = main.get_tree()
	var srv_root := Node.new()
	srv_root.name = "CrashReportSrv"
	tree.root.add_child(srv_root)
	tree.set_multiplayer(SceneMultiplayer.new(), srv_root.get_path())
	var cli_root := Node.new()
	cli_root.name = "CrashReportCli"
	tree.root.add_child(cli_root)
	var cli_mp := SceneMultiplayer.new()
	tree.set_multiplayer(cli_mp, cli_root.get_path())
	var hs = load("res://scripts/server/local_server.gd").new()
	hs.autosave_enabled = false
	hs.store_dir = ROOT + "/srv/chars"
	hs.emit_snapshots = false
	hs.name = "CrashSrvGame"
	srv_root.add_child(hs)
	var ns = load("res://scripts/net/net_server.gd").new()
	ns.server = hs
	ns.data_root = ROOT + "/srv"
	ns.dedicated = true
	ns.pw_iter = 200
	ns.bind_ip = "127.0.0.1"
	ns.slog = ServerLog.new(ROOT + "/srv", false)
	srv_root.add_child(ns)
	# the test server makes its own TLS key pair in the test folder (config.json "tls_dir" points at the real server's)
	var had_tls := GameData.config.has("tls_dir")
	var tls_was = GameData.config.get("tls_dir", "")
	GameData.config["tls_dir"] = ROOT + "/srv/tls"
	var port := 0
	for i in 6:
		var p := 26100 + randi() % 2800
		if ns.start(p) == "":
			port = p
			break
	if had_tls:
		GameData.config["tls_dir"] = tls_was
	else:
		GameData.config.erase("tls_dir")
	check(port > 0, "test server listens on 127.0.0.1:%d" % port)
	if port == 0:
		await _cleanup(main, w2, srv_root, cli_root, ns, null)
		return
	check(ns.store.register(USER, PW) == "", "test account")
	var rs = load("res://scripts/net/remote_server.gd").new()
	rs.ch = CharacterState.new()
	cli_root.add_child(rs)
	var err: String = rs.connect_to("127.0.0.1", port, USER, PW, "login", CHAR)
	var played: bool = err == "" and await wait_for(main, func(): return str(rs.state) == "playing", 900)
	check(played, "the client logs in and plays %s on the test server (%s, %s)" % [CHAR, err, str(rs.state)])
	if not played:
		await _cleanup(main, w2, srv_root, cli_root, ns, rs)
		return
	# 3. the pending crash report goes out after the login
	w2.net = rs
	var day := Time.get_datetime_string_from_system().left(10).replace("-", "")
	var rdir := ROOT + "/srv/reports/crash/" + day
	var got := await wait_for(main, func(): return ns.slog.has_line("CRASHREPORT %s/%s crash" % [USER, CHAR]) and w2.pending_files().is_empty(), 600)
	var files: Array = Array(DirAccess.get_files_at(rdir)) if DirAccess.dir_exists_absolute(rdir) else []
	var crash_file := ""
	for fn in files:
		var fd = JSON.parse_string(FileAccess.get_file_as_string(rdir.path_join(fn)))
		if str(fn).begins_with("%s_%s_" % [USER, CHAR]) and fd is Dictionary and str(fd.get("reason", "")) == "crash":
			crash_file = str(fn)
	check(got and crash_file != "",
		"the crash report arrives: reports/crash/%s/%s, 'CRASHREPORT %s/%s crash' logged, pending copies deleted on the ack" % [day, str(files), USER, CHAR])
	if crash_file != "":
		var stored := FileAccess.get_file_as_string(rdir.path_join(crash_file))
		var sd = JSON.parse_string(stored)
		check(sd is Dictionary and str(sd.get("user", "")) == USER and str(sd.get("char", "")) == CHAR and str(sd.get("reason", "")) == "crash"
			and (sd.get("report", {}) as Dictionary).has("log") and not stored.contains("hunter2") and not stored.contains("203.0.113.7"),
			"the stored file has user, character, reason, the log tail - and no secrets")
	# 4. a hang: the main loop stalls longer than the watchdog limit
	w2.hang_s = 2.0
	# the context the watchdog reports (normally main.map_id + main.auto, captured every 0.5 s)
	w2._ctx = {"map": "hanamura_outskirts", "auto": "on battle hunting Pudding Slime", "target": "Pudding Slime #77", "net": "playing"}
	w2._ctx_t = 999.0
	await frames(main, 3)
	var t0 := Time.get_ticks_msec()
	OS.delay_msec(3200)
	var stalled := Time.get_ticks_msec() - t0
	var hung := await wait_for(main, func(): return ns.slog.has_line("CRASHREPORT %s/%s hang" % [USER, CHAR]), 600)
	check(hung, "a %.1f s main-loop stall is recorded by the watchdog thread and sent on recovery ('CRASHREPORT %s/%s hang')" % [stalled / 1000.0, USER, CHAR])
	var hang_line := ""
	for l in ns.slog.recent:
		if str(l).contains("CRASHREPORT %s/%s hang" % [USER, CHAR]):
			hang_line = str(l)
	check(hang_line.contains("hunting Pudding Slime"), "the hang carries the last AUTO state (%s)" % hang_line.right(100))
	var hrep = _newest_report(rdir, "hang")
	check(hrep is Dictionary and bool(hrep["report"]["hang"].get("recovered", false)) and float(hrep["report"]["hang"].get("stalled_s", 0)) >= 2.0
		and str(hrep["report"]["hang"].get("target", "")) == "Pudding Slime #77",
		"stored hang report: recovered, stalled %.1f s, AUTO target" % (float(hrep["report"]["hang"].get("stalled_s", 0)) if hrep is Dictionary else -1.0))
	w2.hang_s = CrashWatch.HANG_S
	w2._ctx_t = 0.0
	w2.main_node = main
	# 5. script errors: a rate-limited batch (the timer is held here; the test sends the batch itself)
	w2._err_t = 999.0
	push_error("crashreport test: deliberate script error token=zzz - ignore this line")
	push_error("crashreport test: deliberate script error token=zzz - ignore this line")
	await frames(main, 3)
	var n_err0 := _count(ns, "CRASHREPORT %s/%s script_error" % [USER, CHAR])
	w2.report_errors()
	var errs_in := await wait_for(main, func(): return _count(ns, "CRASHREPORT %s/%s script_error" % [USER, CHAR]) > n_err0 and w2.pending_files().is_empty(), 600)
	var erep = _newest_report(rdir, "script_error")
	var elist: Array = erep["report"].get("errors", []) if erep is Dictionary else []
	check(errs_in and elist.size() == 1 and int(elist[0].get("n", 0)) == 2 and not JSON.stringify(erep).contains("zzz"),
		"script errors go out as one deduplicated, sanitized batch (%s)" % str(elist).left(120))
	w2.report_errors()
	check(w2.pending_files().is_empty(), "no new errors: no new error report")
	# 6. disconnect reasons
	rs.close()
	var quit_ok := await wait_for(main, func(): return _has(ns, "logout %s (%s)" % [CHAR, USER], "reason=quit"), 300)
	check(quit_ok, "a client that quits says bye: 'logout %s (%s) ... reason=quit'" % [CHAR, USER])
	# closed without a bye (killed client / network reset)
	err = rs.connect_to("127.0.0.1", port, USER, PW, "login", CHAR)
	played = err == "" and await wait_for(main, func(): return str(rs.state) == "playing", 900)
	if played:
		await frames(main, 30)
		var p1: ENetMultiplayerPeer = rs.peer
		rs.peer = null
		rs.state = "closed"
		p1.close()
		var drop_ok := await wait_for(main, func(): return _has(ns, "logout %s (%s)" % [CHAR, USER], "reason=drop"), 300)
		check(drop_ok, "a connection closed without bye: 'reason=drop'")
	else:
		check(false, "second login for the drop test (%s)" % err)
	var frozen = null
	# silence: the client stops answering; ENet times out (short timeouts on the test server)
	err = rs.connect_to("127.0.0.1", port, USER, PW, "login", CHAR)
	played = err == "" and await wait_for(main, func(): return str(rs.state) == "playing", 900)
	if played:
		await frames(main, 30)
		var fs: Array = ns.find_session(CHAR)
		if not fs.is_empty():
			ns.peer.get_peer(int(fs[0])).set_timeout(32, 2000, 3000)
		rs.state = "frozen"
		tree.set_multiplayer(null, cli_root.get_path())
		var to_ok := await wait_for(main, func(): return _has(ns, "logout %s (%s)" % [CHAR, USER], "reason=timeout"), 900)
		check(to_ok, "a client that goes silent: 'reason=timeout last_packet=...'")
		# the frozen client's connection is closed after the server (its late disconnect would reach a server that already
		# dropped it: a DTLS handshake error in the log)
		frozen = rs.peer
		rs.peer = null
		rs.state = "closed"
	else:
		check(false, "third login for the timeout test (%s)" % err)
	await _cleanup(main, w2, srv_root, cli_root, ns, rs, frozen)


static func _count(ns, a: String) -> int:
	var n := 0
	for l in ns.slog.recent:
		if str(l).contains(a):
			n += 1
	return n


static func _has(ns, a: String, b: String) -> bool:
	for l in ns.slog.recent:
		if str(l).contains(a) and str(l).contains(b):
			return true
	return false


static func _newest_report(rdir: String, reason: String):
	var best = null
	if not DirAccess.dir_exists_absolute(rdir):
		return null
	for fn in DirAccess.get_files_at(rdir):
		var d = JSON.parse_string(FileAccess.get_file_as_string(rdir.path_join(fn)))
		if d is Dictionary and str(d.get("reason", "")) == reason:
			if best == null or int(d.get("received_unix", 0)) >= int(best.get("received_unix", 0)):
				best = d
	return best


static func _cleanup(main: Node, w2, srv_root: Node, cli_root: Node, ns, rs, frozen = null) -> void:
	var tree: SceneTree = main.get_tree()
	if rs != null and rs.peer != null:
		rs.state = "closed"
		rs.peer.close()
	if ns != null and ns.peer != null:
		ns.shutdown("crashreport test over")
	if frozen != null:
		frozen.close()
	await frames(main, 2)
	tree.set_multiplayer(null, srv_root.get_path())
	tree.set_multiplayer(null, cli_root.get_path())
	srv_root.queue_free()
	cli_root.queue_free()
	if w2 != null and is_instance_valid(w2):
		w2.stop(true)
		check(not FileAccess.file_exists(w2.dir + "/session.json"), "a clean exit removes the marker")
		main.remove_child(w2)
		w2.free()
	await frames(main, 2)


static func _write(path: String, text: String) -> void:
	var f := FileAccess.open(path, FileAccess.WRITE)
	if f:
		f.store_string(text)
		f.close()


static func _rm_tree(path: String) -> void:
	if not DirAccess.dir_exists_absolute(path):
		return
	for d in DirAccess.get_directories_at(path):
		_rm_tree(path.path_join(d))
	for fn in DirAccess.get_files_at(path):
		DirAccess.remove_absolute(path.path_join(fn))
	DirAccess.remove_absolute(path)
