// pvp2mvm_diag.nut - read-only: prints which objective entities the map has right now, to chat and console.
// Run with: sm_script_execute pvp2mvm_diag
local function Say(msg)
{
	printl("[pvp2mvm diag] " + msg)
	ClientPrint(null, 3, "[diag] " + msg)
}

Say("map " + GetMapName())
foreach (cls in ["team_train_watcher", "func_tracktrain", "path_track", "team_control_point_master",
	"team_control_point", "trigger_capture_area", "team_round_timer", "item_teamflag", "func_capturezone",
	"tf_logic_mann_vs_machine", "info_populator", "func_upgradestation", "func_regenerate"])
{
	local count = 0
	local names = []
	for (local ent; ent = Entities.FindByClassname(ent, cls);)
	{
		count++
		if (names.len() < 4)
			names.append(ent.GetName() == "" ? "(no name)" : ent.GetName())
	}
	Say(cls + ": " + count + (count > 0 ? "  " + names.reduce(@(a, b) a + ", " + b) : ""))
}

// the payload: watcher settings, and a walk along the track from its start node
for (local w; w = Entities.FindByClassname(w, "team_train_watcher");)
{
	local start = NetProps.GetPropString(w, "m_iszStartNode")
	local goal = NetProps.GetPropString(w, "m_iszGoalNode")
	local train = NetProps.GetPropString(w, "m_iszTrain")
	Say(format("watcher '%s': train '%s' (%s), start '%s' (%s), goal '%s' (%s), disabled %d", w.GetName(),
		train, Entities.FindByName(null, train) != null ? "found" : "MISSING",
		start, Entities.FindByName(null, start) != null ? "found" : "MISSING",
		goal, Entities.FindByName(null, goal) != null ? "found" : "MISSING",
		NetProps.GetPropInt(w, "m_bDisabled")))
}
local node = Entities.FindByName(null, "minecart_path_1")
local steps = 0, seen = {}, last = "none"
while (node != null && !(node in seen) && steps < 400)
{
	seen[node] <- true
	steps++
	last = node.GetName()
	local next = NetProps.GetPropString(node, "m_target")
	node = next == "" ? null : Entities.FindByName(null, next)
}
Say("track walk from minecart_path_1: " + steps + " nodes, ends at " + last)
local cart = Entities.FindByName(null, "minecart_tracktrain")
if (cart != null)
	Say("cart at " + cart.GetOrigin().ToKVString() + ", speed " + NetProps.GetPropFloat(cart, "m_flSpeed"))
for (local gr = Entities.FindByClassname(null, "tf_gamerules"); gr != null; gr = null)
	Say("hud type " + NetProps.GetPropInt(gr, "m_nHudType"))

// which of the map's track nodes (minecart_path_1..174) are gone, and what the other path_tracks are
local missing = []
for (local i = 1; i <= 174; i++)
	if (Entities.FindByName(null, "minecart_path_" + i) == null)
		missing.append(i)
Say("minecart_path nodes missing: " + missing.len() + (missing.len() > 0 && missing.len() <= 20 ? "  " + missing.map(@(i) i.tostring()).reduce(@(a, b) a + " " + b) : ""))
local others = {}
for (local p; p = Entities.FindByClassname(p, "path_track");)
{
	local name = p.GetName()
	if (name.find("minecart_path_") == 0)
		continue
	if (name == "")
	{
		Say("unnamed path_track at " + p.GetOrigin().ToKVString() + " -> " + NetProps.GetPropString(p, "m_target"))
		continue
	}
	// group the rest by prefix (tank_path_a_, ...)
	local prefix = name
	local cut = name.len()
	while (cut > 0 && name[cut - 1] >= '0' && name[cut - 1] <= '9')
		cut--
	prefix = name.slice(0, cut)
	others[prefix] <- (prefix in others ? others[prefix] : 0) + 1
}
foreach (prefix, count in others)
	Say("other path_tracks " + prefix + "*: " + count)
for (local p; p = Entities.FindByClassname(p, "path_track");)
	if (NetProps.GetPropString(p, "m_target") == "minecart_path_2")
		Say("node before minecart_path_2: '" + p.GetName() + "' at " + p.GetOrigin().ToKVString())

// the cart's capture area and the watcher's link to it
for (local a; a = Entities.FindByClassname(a, "trigger_capture_area");)
	Say(format("capture area '%s': point '%s', disabled %d, parent %s", a.GetName(), NetProps.GetPropString(a, "m_iszCapPointName"),
		NetProps.GetPropInt(a, "m_bDisabled"), a.GetMoveParent() != null ? a.GetMoveParent().GetName() : "none"))

// can anyone capture: point owners / locks, the watcher's state
for (local cp; cp = Entities.FindByClassname(cp, "team_control_point");)
{
	local locked = "?"
	try { locked = NetProps.GetPropBool(cp, "m_bLocked") ? "LOCKED" : "unlocked" } catch (e) {}
	Say(format("point %s: owner team %d, %s, disabled %d", cp.GetName(), cp.GetTeam(), locked, NetProps.GetPropInt(cp, "m_bDisabled")))
}
for (local w; w = Entities.FindByClassname(w, "team_train_watcher");)
	Say(format("watcher disabled %d, train speed %.0f", NetProps.GetPropInt(w, "m_bDisabled"),
		NetProps.GetPropFloat(Entities.FindByName(null, "minecart_tracktrain"), "m_flSpeed")))
for (local m; m = Entities.FindByClassname(m, "team_control_point_master");)
	Say(format("master disabled %d", NetProps.GetPropInt(m, "m_bDisabled")))
for (local r; r = Entities.FindByClassname(r, "team_control_point_round");)
	Say(format("round %s: disabled %d", r.GetName(), NetProps.GetPropInt(r, "m_bDisabled")))

// what the script thinks each robot is doing
if ("PvP2MvM" in getroottable())
{
	local P = ::PvP2MvM
	local cart = P.FindCart()
	Say(format("script: cart %s, pushers %d, bomb mode %s, populator %s, think ents %d/%d", cart != null ? "found" : "NONE",
		P.Pushers.len(), P.Cfg("BombMode").tostring(), P.UsePopulator().tostring(),
		Entities.FindByName(null, "pvp2mvm_cart_think") != null ? 1 : 0, Entities.FindByName(null, "pvp2mvm_think") != null ? 1 : 0))
	Say(format("cart drive: repaired %s, pushers sent to watcher %d", P.CartRepaired.tostring(), P.CartCappers))
	// the robot pool: bots by team (0 unassigned, 1 spectator, 2 RED, 3 BLU), alive or not, and humans
	local teams = [0, 0, 0, 0], alive = 0, humans = 0
	foreach (player in P.Players())
	{
		if (!IsPlayerABot(player)) { humans++; continue }
		local t = player.GetTeam()
		if (t >= 0 && t <= 3) teams[t]++
		if (t == 3 && P.IsAlive(player)) alive++
	}
	Say(format("players: %d humans; bots unassigned %d, spectator %d, RED %d, BLU %d (alive %d); maxplayers %d; tf_bot_quota %s",
		humans, teams[0], teams[1], teams[2], teams[3], alive, MaxClients().tointeger(), Convars.GetStr("tf_bot_quota")))
	local wave = Entities.FindByClassname(null, "tf_objective_resource")
	if (wave != null)
		Say(format("wave %d of %d", NetProps.GetPropInt(wave, "m_nMannVsMachineWaveCount"), NetProps.GetPropInt(wave, "m_nMannVsMachineMaxWaveCount")))
	local shown = 0
	foreach (bot in P.Players())
	{
		if (!IsPlayerABot(bot) || bot.GetTeam() != 3 || !P.IsAlive(bot) || shown >= 8)
			continue
		shown++
		local i = bot.entindex()
		local walked = P.Cfg("WalkedClasses").find(bot.GetPlayerClass()) != null
		Say(format("robot %s class %d: %s%s, %.0fu from cart, route %s, mission %d", NetProps.GetPropString(bot, "m_szNetname"),
			bot.GetPlayerClass(), !walked ? "not walked" : (i in P.Pushers ? "PUSHER" : (i in P.HunterState ? "hunter" : "no role yet")),
			i in P.LeaderOf ? " (squad)" : "", cart != null ? (bot.GetOrigin() - cart.GetOrigin()).Length() : -1,
			i in P.CartState ? P.CartState[i].path.len() + " points" : "none", bot.IsOnAnyMission() ? 1 : 0))
	}
}

// robot spawn points: ours are entity_saucer (kept across restarts), anything else under these names isn't ours
local spawnCounts = {}
for (local s; s = Entities.FindByName(s, "spawnbot*");)
{
	local o = s.GetOrigin()
	local key = format("%s %s %s at %d %d %d", s.GetName(), s.GetClassname(),
		NetProps.GetPropBool(s, "m_bDisabled") ? "OFF" : "on", o.x.tointeger(), o.y.tointeger(), o.z.tointeger())
	spawnCounts[key] <- (key in spawnCounts ? spawnCounts[key] : 0) + 1
}
local spawnLines = 0
foreach (key, count in spawnCounts)
	if (key.find("spawnbot ") == 0 && spawnLines++ < 12)   // just the plain "spawnbot" name - the rest copy it
		Say("spawn point " + key + (count > 1 ? " x" + count : ""))

// every BLU spawn point the map / server has (not ours), grouped by name + on/off, with where the first one is
local bluSpawns = {}
for (local s; s = Entities.FindByClassname(s, "info_player_teamspawn");)
{
	if (s.GetTeam() != 3)
		continue
	local key = (s.GetName() == "" ? "(no name)" : s.GetName()) + (NetProps.GetPropBool(s, "m_bDisabled") ? " OFF" : " on")
	if (!(key in bluSpawns))
	{
		local o = s.GetOrigin()
		bluSpawns[key] <- { count = 0, at = format("%d %d %d", o.x.tointeger(), o.y.tointeger(), o.z.tointeger()) }
	}
	bluSpawns[key].count++
}
foreach (key, info in bluSpawns)
	Say("BLU spawn " + key + " x" + info.count + " (first at " + info.at + ")")

// the cart's own state and the links it actually follows (m_pnext pointers, not names)
local function EntName(ent) { return ent == null ? "null" : (ent.GetName() == "" ? "(no name)" : ent.GetName()) }
local train = Entities.FindByName(null, "minecart_tracktrain")
if (train != null)
{
	local path = null
	try { path = NetProps.GetPropEntity(train, "m_ppath") } catch (e) {}
	Say(format("train: path node %s, velocity %s, movetype %d, solid %d, dir %s", EntName(path), train.GetAbsVelocity().ToKVString(),
		train.GetMoveType(), train.GetSolid(), (function() { try { return NetProps.GetPropFloat(train, "m_dir").tostring() } catch (e) { return "?" } })()))
}
foreach (n in ["minecart_path_1", "minecart_path_2", "minecart_path_3"])
	for (local node; node = Entities.FindByName(node, n);)
	{
		local next = null, prev = null, alt = null
		try { next = NetProps.GetPropEntity(node, "m_pnext") } catch (e) {}
		try { prev = NetProps.GetPropEntity(node, "m_pprevious") } catch (e) {}
		try { alt = NetProps.GetPropEntity(node, "m_paltpath") } catch (e) {}
		Say(format("node %s: next %s, prev %s, alt %s, spawnflags %d", n, EntName(next), EntName(prev), EntName(alt),
			NetProps.GetPropInt(node, "m_spawnflags")))
	}

// bot hints (engineer nests / sniper spots): on or off, where
foreach (cls in ["bot_hint_engineer_nest", "bot_hint_sentrygun", "bot_hint_teleporter_exit", "func_tfbot_hint"])
	for (local h; h = Entities.FindByClassname(h, cls);)
	{
		local o = h.GetOrigin()
		local off = "?"
		try { off = NetProps.GetPropBool(h, "m_isDisabled") ? "OFF" : "on" } catch (e) {}
		Say(format("hint %s '%s' %s at %d %d %d", cls, h.GetName(), off, o.x.tointeger(), o.y.tointeger(), o.z.tointeger()))
	}

// robot engineers: where they are, how far from the nest that's up now, and their buildings
local nest = Entities.FindByClassname(null, "bot_hint_engineer_nest")
for (local p = 1; p <= MaxClients().tointeger(); p++)
{
	local e = PlayerInstanceFromIndex(p)
	if (e == null || !IsPlayerABot(e) || e.GetTeam() != 3 || e.GetPlayerClass() != 9 || NetProps.GetPropInt(e, "m_lifeState") != 0)
		continue
	local o = e.GetOrigin()
	local tele = "?"
	try { tele = e.HasBotAttribute(Constants.FTFBotAttributeType.TELEPORT_TO_HINT) ? "TeleportToHint" : "walks" } catch (err) {}
	Say(format("engineer %s (%s) at %d %d %d, %s", NetProps.GetPropString(e, "m_szNetname"), tele, o.x.tointeger(), o.y.tointeger(),
		o.z.tointeger(), nest != null ? format("%.0fu from nest '%s'", (o - nest.GetOrigin()).Length(), nest.GetName()) : "no nest up"))
	foreach (cls in ["obj_sentrygun", "obj_teleporter", "obj_dispenser"])
		for (local b; b = Entities.FindByClassname(b, cls);)
			if (NetProps.GetPropEntity(b, "m_hBuilder") == e)
			{
				local bo = b.GetOrigin()
				Say(format("  its %s '%s' at %d %d %d, health %d", cls, b.GetName(), bo.x.tointeger(), bo.y.tointeger(), bo.z.tointeger(), b.GetHealth()))
			}
}

// what's sitting where the cart starts (the cart you see, if it isn't the real one)
for (local e; e = Entities.FindInSphere(e, Vector(-1674, -1536, 58), 160.0);)
{
	local cls = e.GetClassname()
	if (cls == "player" || cls.find("info_") == 0 || cls.find("tf_") == 0 || cls == "env_spritetrail")
		continue
	local parent = e.GetMoveParent()
	Say(format("near cart start: %s '%s' %s%s", cls, e.GetName(), e.GetModelName(),
		parent != null ? " parent " + parent.GetName() : ""))
}
