#include "teamplay.qh"

#include <common/deathtypes/all.qh>
#include <common/gametypes/_mod.qh>
#include <common/teams.qh>
#include <server/bot/api.qh>
#include <server/bot/default/cvars.qh>
#include <server/campaign.qh>
#include <server/client.qh>
#include <server/command/vote.qh>
#include <server/damage.qh>
#include <server/gamelog.qh>
#include <server/mutators/_mod.qh>
#include <server/race.qh>
#include <server/scores.qh>
#include <server/scores_rules.qh>

/// \brief Describes a state of team balance data entity.
enum
{
	TEAM_BALANCE_UNINITIALIZED, ///< The team balance has not been initialized.
	/// \brief TeamBalance_CheckAllowedTeams has been called.
	TEAM_BALANCE_TEAMS_CHECKED,
	/// \brief TeamBalance_GetTeamCounts has been called.
	TEAM_BALANCE_TEAM_COUNTS_FILLED
};

/// \brief Indicates that the player is not allowed to join a team.
const int TEAM_NOT_ALLOWED = -1;

.int m_team_balance_state; ///< Holds the state of the team balance data entity.
.entity m_team_balance_team[NUM_TEAMS]; ///< ???

.float m_team_score; ///< The score of the team.
.int m_num_players; ///< Number of players (both humans and bots) in a team.
.int m_num_players_net; ///< .m_num_players but excluding bots that would leave if a human joined their team.
.int m_num_bots; ///< Number of bots in a team.
.int m_num_players_alive; ///< Number of alive players in a team.
.int m_num_owned_items; ///< Number of items owned by a team.

string autocvar_g_forced_team_red;
string autocvar_g_forced_team_blue;
string autocvar_g_forced_team_yellow;
string autocvar_g_forced_team_pink;

entity g_team_entities[NUM_TEAMS]; ///< Holds global team entities.

void _SpawnTeam(string teament_classname, int team_num)
{
	entity this = new_pure(teament_classname);
	this.netname = Static_Team_ColorName(team_num);
	this.cnt = team_num - 1;
	this.spawnfunc_checked = true;
	this.team = team_num;
}
int Team_MapEnts_FindOrSpawn(string ent_classname, int defaultmask)
{
	int teams = 0;
	entity head = findchain(classname, ent_classname);
	while (head)
	{
		if (Team_IsValidTeam(head.team))
			teams |= Team_TeamToBit(head.team);
		head = head.chain;
	}
	if (teams)
		return teams;

	LOG_TRACEF("No \"%s\" entities found on this map, creating them anyway.", ent_classname);
	for (int i = 1; i <= NUM_TEAMS; ++i)
		if (defaultmask & Team_IndexToBit(i))
			_SpawnTeam(ent_classname, Team_IndexToTeam(i));
	return defaultmask;
}

void Team_InitTeams()
{
	if (g_team_entities[0])
		return;
	for (int i = 0; i < AVAILABLE_TEAMS; ++i)
	{
		g_team_entities[i] = new_pure(team_entity);
	}
}

entity Team_GetTeamFromIndex(int index)
{
	if (!Team_IsValidIndex(index))
	{
		LOG_FATALF("Index is invalid: %f", index);
	}
	return g_team_entities[index - 1];
}

entity Team_GetTeam(int team_num)
{
	if (!Team_IsValidTeam(team_num))
	{
		LOG_FATALF("Value is invalid: %f", team_num);
	}
	return g_team_entities[Team_TeamToIndex(team_num) - 1];
}

float Team_GetTeamScore(entity team_ent)
{
	return team_ent.m_team_score;
}

void Team_SetTeamScore(entity team_ent, float score)
{
	team_ent.m_team_score = score;
}

int Team_GetNumberOfAlivePlayers(entity team_ent)
{
	return team_ent.m_num_players_alive;
}

void Team_SetNumberOfAlivePlayers(entity team_ent, int number)
{
	team_ent.m_num_players_alive = number;
}

int Team_GetWinnerAliveTeam()
{
	int winner = 0;
	for (int i = 0; i < AVAILABLE_TEAMS; ++i)
	{
		if (g_team_entities[i].m_num_players_alive > 0)
		{
			if (winner)
				return 0;
			winner = Team_IndexToTeam(i + 1);
		}
	}
	return (winner ? winner : -1);
}

int Team_GetNumberOfAliveTeams()
{
	int result = 0;
	for (int i = 0; i < AVAILABLE_TEAMS; ++i)
	{
		if (g_team_entities[i].m_num_players_alive > 0)
		{
			++result;
		}
	}
	return result;
}

int Team_GetWinnerTeam_WithOwnedItems(int min_control_points)
{
	int winner = 0;
	for (int i = 0; i < AVAILABLE_TEAMS; ++i)
	{
		if (g_team_entities[i].m_num_owned_items >= min_control_points)
		{
			if (winner)
				return 0;
			winner = Team_IndexToTeam(i + 1);
		}
	}
	return (winner ? winner : -1);
}

int Team_GetNumberOfOwnedItems(entity team_ent)
{
	return team_ent.m_num_owned_items;
}

void Team_SetNumberOfOwnedItems(entity team_ent, int number)
{
	team_ent.m_num_owned_items = number;
}

int Team_GetNumberOfTeamsWithOwnedItems()
{
	int result = 0;
	for (int i = 0; i < AVAILABLE_TEAMS; ++i)
	{
		if (g_team_entities[i].m_num_owned_items > 0)
		{
			++result;
		}
	}
	return result;
}

void setcolor(entity this, int clr)
{
#if 1
	this.clientcolors = clr;
	if(teamplay)
		this.team = (clr & 15) + 1;
	else
		this.team = -1;
#else
	// sets clientcolors and team (even in FFA games)
	// and sends notification to all clients
	builtin_setcolor(this, clr);
#endif
}

bool Entity_HasValidTeam(entity this)
{
	return Team_IsValidTeam(this.team);
}

int Entity_GetTeamIndex(entity this)
{
	return Team_TeamToIndex(this.team);
}

entity Entity_GetTeam(entity this)
{
	int index = Entity_GetTeamIndex(this);
	if (!Team_IsValidIndex(index))
	{
		return NULL;
	}
	return Team_GetTeamFromIndex(index);
}

void SetPlayerColors(entity player, float _color)
{
	float pants = _color & 0x0F;
	float shirt = _color & 0xF0;
	if (teamplay)
	{
		setcolor(player, 16 * pants + pants);
	}
	else
	{
		setcolor(player, shirt + pants);
	}
}

bool Player_SetTeamIndex(entity player, int index)
{
	int new_team = Team_IndexToTeam(index);
	if (player.team == new_team)
		return true;

	int old_index = Team_TeamToIndex(player.team);
	if (MUTATOR_CALLHOOK(Player_ChangeTeam, player, old_index, index) == true)
	{
		// Mutator has blocked team change.
		return false;
	}
	if (new_team == -1)
	{
		if (teamplay) // sanity check, if false this code path should never be reached anyway
			player.clientcolors = 0;
		player.team = -1;
	}
	else
	{
		SetPlayerColors(player, new_team - 1);
	}
	MUTATOR_CALLHOOK(Player_ChangedTeam, player, old_index, index);
	return true;
}

/** Returns true when enough players are queued that the next will join directly
 * to the only available team (also triggering the joins of the queued players).
 * Optionally only counts players who selected a specific team when joining the queue.
 */
bool QueuedPlayersReady(entity this, bool checkspecificteam)
{
	int numplayersqueued = 0;

	FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != this
	&& (checkspecificteam ? it.wants_join > 0 : it.wants_join),
	{
		LOG_DEBUGF("Player %s is waiting to join team %d", it.netname, it.wants_join);
		++numplayersqueued;
		if (numplayersqueued >= AVAILABLE_TEAMS - 1)
			return true;
	});

	LOG_DEBUG("No players waiting to join.");
	return false;
}

bool SetPlayerTeam(entity player, int team_index, int type)
{
	int old_team_index = Entity_GetTeamIndex(player);

	if (!Player_SetTeamIndex(player, team_index))
		return false;

	LogTeamChange(player.playerid, player.team, type);

	if (team_index != old_team_index)
	{
		if (!IS_DEAD(player))
			Damage(player, player, player, INFINITY, DEATH_TEAMCHANGE.m_id, DMG_NOWEP, player.origin, '0 0 0');
		PlayerScore_Clear(player);

		if (!IS_BOT_CLIENT(player))
			TeamBalance_AutoBalanceBots();

		if (team_index != -1)
		{
			Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(player.team, INFO_JOIN_PLAY_TEAM), player.netname);
			player.team_selected = team_index; // no autoselect in Join()

			if (warmup_stage)
				ReadyCount(); // teams might be balanced now
		}
	}

	if (team_index == -1)
	{
		if (autocvar_sv_maxidle_playertospectator > 0 && CS(player).idlekick_lasttimeleft)
		{
			// this done here so it happens even when manually speccing during the countdown
			Kill_Notification(NOTIF_ONE_ONLY, player, MSG_CENTER, CPID_IDLING);
			CS(player).idlekick_lasttimeleft = 0;
		}
		else if (!CS(player).just_joined && player.frags != FRAGS_SPECTATOR)
		{
			Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_SPECTATE, player.netname);
		}
	}

	return true;
}

bool MoveToTeam(entity client, int team_index, int type)
{
	//PrintToChatAll(sprintf("MoveToTeam: %s, %f", client.netname, team_index));
	int lockteams_backup = lockteams;  // backup any team lock
	lockteams = 0;  // disable locked teams
	return = SetPlayerTeam(client, team_index, type);
	lockteams = lockteams_backup;  // restore the team lock
}

bool Player_HasRealForcedTeam(entity player)
{
	return Player_GetForcedTeamIndex(player) > TEAM_FORCE_DEFAULT;
}

void Player_SetForcedTeamIndex(entity player, int team_index)
{
	switch (team_index)
	{
		case TEAM_FORCE_SPECTATOR:
		case TEAM_FORCE_DEFAULT:
		{
			player.team_forced = team_index;
			break;
		}
		default:
		{
			if (!Team_IsValidIndex(team_index))
			{
				LOG_FATAL("Invalid team index.");
			}
			else
			{
				player.team_forced = team_index;
				break;
			}
		}
	}
}

int Player_GetForcedTeamIndex(entity player)
{
	// NB: this is intended to work in !teamplay too

	if (player.team_forced != TEAM_FORCE_DEFAULT)
		return player.team_forced; // internally forced spec set by minigames etc wins

	if (autocvar_g_campaign)
	{
		if (IS_REAL_CLIENT(player)) // only players, not bots
		{
			if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
				return autocvar_g_campaign_forceteam;
			else
				return TEAM_FORCE_DEFAULT;
		}
	}
	else if (PlayerInList(player, autocvar_g_forced_team_red))
		return 1;
	else if (PlayerInList(player, autocvar_g_forced_team_blue))
		return 2;
	else if (PlayerInList(player, autocvar_g_forced_team_yellow))
		return 3;
	else if (PlayerInList(player, autocvar_g_forced_team_pink))
		return 4;
	else
	{
		switch (autocvar_g_forced_team_otherwise)
		{
			case "red":
				return 1;
			case "blue":
				return 2;
			case "yellow":
				return 3;
			case "pink":
				return 4;
			case "spectate":
			case "spectator":
				return TEAM_FORCE_SPECTATOR;
		}
	}
	return TEAM_FORCE_DEFAULT;
}

void TeamBalance_JoinBestTeam(entity player)
{
	//PrintToChatAll(sprintf("TeamBalance_JoinBestTeam: %s", player.netname));
	entity balance = TeamBalance_CheckAllowedTeams(player);
	int best_team_index = TeamBalance_FindBestTeam(balance, player, true);
	TeamBalance_Destroy(balance);
	SetPlayerTeam(player, best_team_index, TEAM_CHANGE_AUTO);
}

entity TeamBalance_CheckAllowedTeams(entity for_whom)
{
	entity balance = spawn();
	for (int i = 0; i < AVAILABLE_TEAMS; ++i)
	{
		entity team_ent = balance.m_team_balance_team[i] = spawn();
		team_ent.m_team_score = g_team_entities[i].m_team_score;
		team_ent.m_num_players = teamplay_bitmask & BIT(i) ? 0 : TEAM_NOT_ALLOWED;
	}
	setthink(balance, TeamBalance_Destroy);
	balance.nextthink = time;

	// TODO: Balance quantity of bots across > 2 teams when bot_vs_human is set (and remove next line)
	if (autocvar_bot_vs_human && AVAILABLE_TEAMS == 2 && for_whom)
	{
		if (autocvar_bot_vs_human > 0)
		{
			// find last team available
			if (IS_BOT_CLIENT(for_whom))
			{
				if (TeamBalance_IsTeamAllowedInternal(balance, 4))
				{
					TeamBalance_BanTeamsExcept(balance, 4);
				}
				else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
				{
					TeamBalance_BanTeamsExcept(balance, 3);
				}
				else
				{
					TeamBalance_BanTeamsExcept(balance, 2);
				}
				// no further cases, we know at least 2 teams exist
			}
			else
			{
				if (TeamBalance_IsTeamAllowedInternal(balance, 1))
				{
					TeamBalance_BanTeamsExcept(balance, 1);
				}
				else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
				{
					TeamBalance_BanTeamsExcept(balance, 2);
				}
				else
				{
					TeamBalance_BanTeamsExcept(balance, 3);
				}
				// no further cases, bots have one of the teams
			}
		}
		else
		{
			// find first team available
			if (IS_BOT_CLIENT(for_whom))
			{
				if (TeamBalance_IsTeamAllowedInternal(balance, 1))
				{
					TeamBalance_BanTeamsExcept(balance, 1);
				}
				else if (TeamBalance_IsTeamAllowedInternal(balance, 2))
				{
					TeamBalance_BanTeamsExcept(balance, 2);
				}
				else
				{
					TeamBalance_BanTeamsExcept(balance, 3);
				}
				// no further cases, we know at least 2 teams exist
			}
			else
			{
				if (TeamBalance_IsTeamAllowedInternal(balance, 4))
				{
					TeamBalance_BanTeamsExcept(balance, 4);
				}
				else if (TeamBalance_IsTeamAllowedInternal(balance, 3))
				{
					TeamBalance_BanTeamsExcept(balance, 3);
				}
				else
				{
					TeamBalance_BanTeamsExcept(balance, 2);
				}
				// no further cases, bots have one of the teams
			}
		}
	}

	if (!for_whom)
	{
		balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
		return balance;
	}

	// if player has a forced team, ONLY allow that one
	int i = Player_GetForcedTeamIndex(for_whom);
	if (i != TEAM_FORCE_DEFAULT)
		TeamBalance_BanTeamsExcept(balance, i);

	balance.m_team_balance_state = TEAM_BALANCE_TEAMS_CHECKED;
	return balance;
}

void TeamBalance_Destroy(entity balance)
{
	if (balance == NULL)
	{
		return;
	}
	for (int i = 0; i < AVAILABLE_TEAMS; ++i)
	{
		delete(balance.(m_team_balance_team[i]));
	}
	delete(balance);
}

int TeamBalance_GetAllowedTeams(entity balance)
{
	if (balance == NULL)
	{
		LOG_FATAL("Team balance entity is NULL.");
	}
	if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
	{
		LOG_FATAL("Team balance entity is not initialized.");
	}
	int result = 0;
	for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
	{
		if (TeamBalance_IsTeamAllowedInternal(balance, i))
		{
			result |= Team_IndexToBit(i);
		}
	}
	return result;
}

int TeamBalance_SizeDifference(entity ignore)
{
	if (!teamplay)
		return 0;

	entity balance = TeamBalance_CheckAllowedTeams(ignore);
	TeamBalance_GetTeamCounts(balance, ignore);

	int ts_min = 255, ts_max = 0;
	for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
	{
		int ts = TeamBalance_GetTeamFromIndex(balance, i).m_num_players;
		if (ts_min > ts)
			ts_min = ts;
		if (ts_max < ts)
			ts_max = ts;
	}

	TeamBalance_Destroy(balance);

	return ts_max - ts_min;
}

bool TeamBalance_AreEqual(entity ignore, bool would_leave)
{
	entity balance = TeamBalance_CheckAllowedTeams(ignore);
	TeamBalance_GetTeamCounts(balance, ignore);

	int prev_size = 0, i = 1;

	for (; i <= AVAILABLE_TEAMS; ++i)
	{
		entity team_ent = TeamBalance_GetTeamFromIndex(balance, i);
		int team_size = would_leave ? team_ent.m_num_players_net : team_ent.m_num_players;
		if (i > 1 && team_size != prev_size)
			break;
		prev_size = team_size;
	}

	TeamBalance_Destroy(balance);
	return i > AVAILABLE_TEAMS;
}

entity remove_countdown;
void Remove_Countdown(entity this)
{
	if(this.lifetime <= 0 || TeamBalance_AreEqual(NULL, false))
	{
		if(this.lifetime <= 0)
		{
			Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_MOVETOSPEC_REMOVE, playername(remove_countdown.enemy.netname, remove_countdown.enemy.team, true));
			PutObserverInServer(remove_countdown.enemy, true, true);
		}

		Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_REMOVE);

		delete(this);
		remove_countdown = NULL;

		TeamBalance_RemoveExcessPlayers(NULL); // Check again for excess players in case someone also left while in countdown
		return;
	}

	--this.lifetime;
	this.nextthink = time + 1;
}

// FIXME: support more than 2 teams, the notification will be... awkward
// FIXME: also don't kick the fc/bc/kc lol
void TeamBalance_RemoveExcessPlayers(entity ignore)
{
	if(AVAILABLE_TEAMS != 2 || autocvar_g_campaign) return;

	entity balance = TeamBalance_CheckAllowedTeams(ignore);
	TeamBalance_GetTeamCounts(balance, ignore);

	int min = 0;

	for(int i = 1; i <= AVAILABLE_TEAMS; ++i)
	{
		int cur = TeamBalance_GetTeamFromIndex(balance, i).m_num_players;
		if(i == 1 || cur < min)
			min = cur;
	}

	for(int tmi = 1; tmi <= AVAILABLE_TEAMS; ++tmi)
	{
		int cur = TeamBalance_GetTeamFromIndex(balance, tmi).m_num_players;
		if(cur > 0 && cur > min) // If this team has excess players
		{
			// Get newest player
			int latest_join = 0;
			entity latest_join_pl = NULL;

			FOREACH_CLIENT(IS_REAL_CLIENT(it) || INGAME(it), {
				if(it.team == Team_IndexToTeam(tmi) && CS(it).startplaytime > latest_join)
				{
					latest_join = CS(it).startplaytime;
					latest_join_pl = it;
				}
			});

			// Force player to spectate
			if(latest_join_pl)
			{
				// Send player to spectate
				if(autocvar_g_balance_teams_remove_wait)
				{
					// Give a warning before moving to spect
					if (!remove_countdown)
					{
						remove_countdown = new_pure(remove_countdown);
						setthink(remove_countdown, Remove_Countdown);
						remove_countdown.nextthink = time;
						Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_MOVETOSPEC_REMOVE, playername(latest_join_pl.netname, latest_join_pl.team, true), autocvar_g_balance_teams_remove_wait);
					}
					remove_countdown.enemy = latest_join_pl;
					remove_countdown.lifetime = autocvar_g_balance_teams_remove_wait;
				}
				else
				{
					// Move to spects immediately
					Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_MOVETOSPEC_REMOVE, latest_join_pl.netname);
					PutObserverInServer(latest_join_pl, true, true);
				}
			}
		}
	}

	TeamBalance_Destroy(balance);
}

bool TeamBalance_QueuedPlayersTagIn(entity ignore)
{
	if (!teamplay)
		return true;

	int j, teamplayers_deficit = 0, teamplayers_max = 0;
	entity it, balance = TeamBalance_CheckAllowedTeams(ignore);
	TeamBalance_GetTeamCounts(balance, ignore);

	for (int j = 1; j <= AVAILABLE_TEAMS; ++j)
	{
		it = TeamBalance_GetTeamFromIndex(balance, j);
		// find the largest team size
		if (it.m_num_players_net > teamplayers_max)
			teamplayers_max = it.m_num_players_net;
	}
	// find how many players we'd need to join to achieve balanced numbers that way
	for (j = 1; j <= AVAILABLE_TEAMS; ++j)
		teamplayers_deficit += teamplayers_max - TeamBalance_GetTeamFromIndex(balance, j).m_num_players_net;

	// first pass: find clients(s) who want to play on a specific team
	for (j = 1; teamplayers_deficit > 0 && j <= maxclients; ++j)
	{
		it = ftoe(j);
		if (it.wants_join <= 0 || it == ignore) continue;
		if (TeamBalance_GetTeamFromIndex(balance, it.wants_join).m_num_players_net >= teamplayers_max) continue;
		Join(it, false);
		++TeamBalance_GetTeam(balance, it.team).m_num_players_net;
		--teamplayers_deficit;
	}

	// second pass: find clients(s) who want to play on any team
	for (j = 1; teamplayers_deficit > 0 && j <= maxclients; ++j)
	{
		it = ftoe(j);
		if (it.wants_join >= 0 || it == ignore) continue;
		Join(it, false);
		--teamplayers_deficit; // don't need to update .m_num_players_net as we won't read it again
	}

	TeamBalance_Destroy(balance);
	return teamplayers_deficit <= 0; // return true if teams are now balanced
}

bool TeamBalance_IsTeamAllowed(entity balance, int index)
{
	if (balance == NULL)
	{
		LOG_FATAL("Team balance entity is NULL.");
	}
	if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
	{
		LOG_FATAL("Team balance entity is not initialized.");
	}
	if (!Team_IsValidIndex(index))
	{
		LOG_FATALF("Team index is invalid: %f",
			index);
	}
	return TeamBalance_IsTeamAllowedInternal(balance, index);
}

// maybe include qcsrc/server/clientkill.qh instead of declaring this?
.int killindicator_teamchange;
void TeamBalance_GetTeamCounts(entity balance, entity ignore)
{
	if (balance == NULL)
		LOG_FATAL("Team balance entity is NULL.");
	if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
		LOG_FATAL("Team balance entity is not initialized.");

	if (MUTATOR_CALLHOOK(TeamBalance_GetTeamCounts) == true)
	{
		// Mutator has overriden the configuration.
		for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
		{
			entity team_ent = TeamBalance_GetTeamFromIndex(balance, i);
			if (TeamBalanceTeam_IsAllowed(team_ent))
			{
				MUTATOR_CALLHOOK(TeamBalance_GetTeamCount, i, ignore);
				team_ent.m_num_players = M_ARGV(2, float);
				team_ent.m_num_bots = M_ARGV(3, float);
			}
		}
	}
	else
	{
		float skill_weight = 0, skill_weight_sum = 0;
		server_skill_average = 0;
		// Manually count all players.
		FOREACH_CLIENT(true,
		{
			if (it.m_skill_mu && it.m_skill_var)
			{
				skill_weight = 1 / it.m_skill_var;
				server_skill_average += it.m_skill_mu * skill_weight;
				skill_weight_sum += skill_weight;
			}

			if (it == ignore)
				continue;

			int team_num = it.killindicator_teamchange > 0 ? it.killindicator_teamchange : it.team;
			if (team_num <= 0)
			{
				int forced_team_index = Player_GetForcedTeamIndex(it);
				if (forced_team_index > TEAM_FORCE_DEFAULT) // Do we really need this? Probably not.
					team_num = Team_IndexToTeam(forced_team_index); // reserve the spot
				else
					continue;
			}
			if (!Team_IsValidTeam(team_num))
				continue;

			entity team_ent = TeamBalance_GetTeam(balance, team_num);
			if (!TeamBalanceTeam_IsAllowed(team_ent))
				continue;

			team_ent.m_num_players_net = ++team_ent.m_num_players;
			if (IS_BOT_CLIENT(it))
				++team_ent.m_num_bots;

			if (it.m_skill_mu && it.m_skill_var)
			{
				// skill_weight calculated above
				team_ent.m_skill_mu += it.m_skill_mu * skill_weight;
				team_ent.mass += skill_weight;
				++team_ent.count;
			}
		});

		// Deduct bots that would leave if a player joined their team;
		// to ensure a player can join we aim to deduct at least one from each team which has some.
		for (int i = 1, bots_maxperteam = ceil(bots_would_leave / AVAILABLE_TEAMS); i <= AVAILABLE_TEAMS; ++i)
		{
			entity team_ent = TeamBalance_GetTeamFromIndex(balance, i);
			team_ent.m_num_players_net -= min(team_ent.m_num_bots, bots_maxperteam);
		}

		// Calculate inverse-variance weighted mean skill ratings,
		// for each unranked client use a fraction of the mean of all clients' skill ratings.
		server_skill_average = (skill_weight_sum && autocvar_g_balance_teams_skill_unranked_factor > 0)
			? autocvar_g_balance_teams_skill_unranked_factor * server_skill_average / skill_weight_sum
			: 1000;
		float server_skill_average_var = 0; skill_weight = 0; // will only be calculated once, if needed
		for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
		{
			entity team_ent = TeamBalance_GetTeamFromIndex(balance, i);
			int unranked_clients = team_ent.m_num_players - team_ent.count; // noobs and bots
			if (unranked_clients)
			{
				if (!server_skill_average_var)
				{
					server_skill_average_var = (server_skill_average * 0.25)**2;
					skill_weight = 1 / server_skill_average_var;
				}
				team_ent.m_skill_mu += (server_skill_average * skill_weight) * unranked_clients;
				team_ent.mass += skill_weight * unranked_clients;
			}
			if (team_ent.mass)
			{
				// .mass is storing the arithmetic sum of members' inverse-variance weightings
				// Hence the team's   mean   is: team_ent.m_skill_mu / team_ent.mass
				// Hence the team's variance is: 1 / team_ent.mass
				team_ent.m_skill_mu /= team_ent.mass;
				team_ent.m_skill_var = 1 / team_ent.mass;
			}
		}
	}

	// if the player who has a forced team has not joined yet, reserve the spot
	if (autocvar_g_campaign)
	if (Team_IsValidIndex(autocvar_g_campaign_forceteam))
	{
		entity team_ent = TeamBalance_GetTeamFromIndex(balance, autocvar_g_campaign_forceteam);
		if (team_ent.m_num_players == team_ent.m_num_bots)
			++team_ent.m_num_players;
	}
	balance.m_team_balance_state = TEAM_BALANCE_TEAM_COUNTS_FILLED;
}

int TeamBalance_GetNumberOfPlayers(entity balance, int index)
{
	if (balance == NULL)
	{
		LOG_FATAL("Team balance entity is NULL.");
	}
	if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
	{
		LOG_FATAL("TeamBalance_GetTeamCounts has not been called.");
	}
	if (!Team_IsValidIndex(index))
	{
		LOG_FATALF("Team index is invalid: %f", index);
	}
	return balance.m_team_balance_team[index - 1].m_num_players;
}

int TeamBalance_FindBestTeam(entity balance, entity player, bool ignore_player)
{
	if (balance == NULL)
	{
		LOG_FATAL("Team balance entity is NULL.");
	}
	if (balance.m_team_balance_state == TEAM_BALANCE_UNINITIALIZED)
	{
		LOG_FATAL("Team balance entity is not initialized.");
	}

	// count how many players are in each team
	TeamBalance_GetTeamCounts(balance, ignore_player ? player : NULL);

	int team_bits = TeamBalance_FindBestTeams(balance, player, true);
	if (team_bits == 0)
	{
		LOG_WARNF("BUG or MISCONFIGURATION: No teams available for %s\n", player.netname);
		return -1; // only spec
	}

	// don't punish players for UI mistakes by changing teams randomly when already on a best team
	if (player.team > 0 && (team_bits & Team_TeamToBit(player.team)))
		return Team_TeamToIndex(player.team);

	RandomSelection_Init();
	for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
	{
		if (team_bits & Team_IndexToBit(i))
		{
			RandomSelection_AddFloat(i, 1, 1);
		}
	}
	return RandomSelection_chosen_float;
}

int TeamBalance_FindBestTeams(entity balance, entity player, bool use_score)
{
	if (balance == NULL)
		LOG_FATAL("Team balance entity is NULL.");
	if (balance.m_team_balance_state != TEAM_BALANCE_TEAM_COUNTS_FILLED)
		LOG_FATAL("TeamBalance_GetTeamCounts has not been called.");

	if (MUTATOR_CALLHOOK(TeamBalance_FindBestTeams, player) == true)
		return M_ARGV(1, float);

	int team_bits = 0;
	int previous_team = 0;
	float player_skill_mu = 0, player_skill_var = 0;
	for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
	{
		if (!TeamBalance_IsTeamAllowedInternal(balance, i))
			continue;
		if (previous_team == 0)
		{
			team_bits = Team_IndexToBit(i);
			previous_team = i;
			continue;
		}

		entity team_i = TeamBalance_GetTeamFromIndex(balance, i);
		entity team_p = TeamBalance_GetTeamFromIndex(balance, previous_team);

		// During warmup the "best" team isn't the smallest or weakest one,
		// that method puts all the noobs on the same team when players join in the "wrong" order.
		// This picks the team(s) whose weighted mean skill differs the most from the joining player's skill,
		// unless they're all close enough in which case it picks smaller team(s).
		// Warmup-only as it must unbalance team sizes in extreme cases, swaps needed should be minimal.
		if (warmup_stage && autocvar_sv_teamnagger && autocvar_g_balance_teams_skill && IS_REAL_CLIENT(player))
		{
			if (!player_skill_mu)
			{
				player_skill_mu = player.m_skill_mu ? player.m_skill_mu : server_skill_average;
				player_skill_var = player.m_skill_var ? player.m_skill_var : (server_skill_average * 0.25)**2;
			}
			// To determine significance, we'll use a z-score of the inverse-variance weightings
			// with an adjustable threshold
			float team_i_z = (team_i.m_skill_mu - player_skill_mu) / sqrt(team_i.m_skill_var + player_skill_var);
			float team_p_z = (team_p.m_skill_mu - player_skill_mu) / sqrt(team_p.m_skill_var + player_skill_var);
			bool significant = fabs(team_i_z - team_p_z) > autocvar_g_balance_teams_skill_significance_threshold;
			// Do fabs afterwards, since the player can be in the middle of the teams (one z +ve, other -ve)
			team_i_z = fabs(team_i_z);
			team_p_z = fabs(team_p_z);

			// NB: if bots were to use this code they'd need .m_num_players instead of .m_num_players_net
			if ((!significant && team_i.m_num_players_net < team_p.m_num_players_net)
			|| ((significant || team_i.m_num_players_net == team_p.m_num_players_net) && team_i_z > team_p_z))
			{
				team_bits = Team_IndexToBit(i);
				previous_team = i;
			}
			else if (team_i_z == team_p_z // unlikely with humans, normal with all bots
			&& team_i.m_num_players_net == team_p.m_num_players_net)
			{
				team_bits |= Team_IndexToBit(i);
				previous_team = i;
			}
			continue;
		}

		int compare = TeamBalance_CompareTeamsInternal(team_i, team_p, player, use_score);
		if (compare == TEAMS_COMPARE_LESS)
		{
			team_bits = Team_IndexToBit(i);
			previous_team = i;
		}
		else if (compare == TEAMS_COMPARE_EQUAL)
		{
			team_bits |= Team_IndexToBit(i);
			previous_team = i;
		}
	}
	return team_bits;
}

void TeamBalance_AutoBalanceBots()
{
	// checks disabled because we always want auto-balanced bots
	//if (!autocvar_g_balance_teams_prevent_imbalance)
	//	return;

	if (intermission_running) return;

	entity balance = TeamBalance_CheckAllowedTeams(NULL);
	TeamBalance_GetTeamCounts(balance, NULL);
	int smallest_team_index = 0;
	int smallest_team_player_count = 0;
	for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
	{
		entity team_ = TeamBalance_GetTeamFromIndex(balance, i);
		if (!TeamBalanceTeam_IsAllowed(team_))
		{
			continue;
		}
		int playercount = TeamBalanceTeam_GetNumberOfPlayers(team_);
		if (smallest_team_index == 0)
		{
			smallest_team_index = i;
			smallest_team_player_count = playercount;
		}
		else if (playercount < smallest_team_player_count)
		{
			smallest_team_index = i;
			smallest_team_player_count = playercount;
		}
	}
	//PrintToChatAll(sprintf("Smallest team: %f", smallest_team_index));
	//PrintToChatAll(sprintf("Smallest team players: %f", smallest_team_player_count));
	entity switchable_bot = NULL;
	int teams = BITS(AVAILABLE_TEAMS);
	while (teams != 0)
	{
		int largest_team_index = TeamBalance_GetLargestTeamIndex(balance,
			teams);
		if (smallest_team_index == largest_team_index)
		{
			TeamBalance_Destroy(balance);
			return;
		}
		entity largest_team = TeamBalance_GetTeamFromIndex(balance,
			largest_team_index);
		int largest_team_player_count = TeamBalanceTeam_GetNumberOfPlayers(
			largest_team);
		if (largest_team_player_count - smallest_team_player_count < 2)
		{
			TeamBalance_Destroy(balance);
			return;
		}
		//PrintToChatAll(sprintf("Largest team: %f", largest_team_index));
		//PrintToChatAll(sprintf("Largest team players: %f", largest_team_player_count));
		switchable_bot = TeamBalance_GetPlayerForTeamSwitch(largest_team_index,
			smallest_team_index, true);
		if (switchable_bot != NULL)
		{
			break;
		}
		teams &= ~Team_IndexToBit(largest_team_index);
	}
	TeamBalance_Destroy(balance);
	if (switchable_bot == NULL)
	{
		//PrintToChatAll("No bot found after searching through all the teams");
		return;
	}
	SetPlayerTeam(switchable_bot, smallest_team_index, TEAM_CHANGE_AUTO);
}

int TeamBalance_GetLargestTeamIndex(entity balance, int teams)
{
	int largest_team_index = 0;
	int largest_team_player_count = 0;
	for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
	{
		if (!(Team_IndexToBit(i) & teams))
		{
			continue;
		}
		entity team_ = TeamBalance_GetTeamFromIndex(balance, i);
		if (!TeamBalanceTeam_IsAllowed(team_))
		{
			continue;
		}
		int playercount = TeamBalanceTeam_GetNumberOfPlayers(team_);
		if (largest_team_index == 0)
		{
			largest_team_index = i;
			largest_team_player_count = playercount;
		}
		else if (playercount > largest_team_player_count)
		{
			largest_team_index = i;
			largest_team_player_count = playercount;
		}
	}
	return largest_team_index;
}

entity TeamBalance_GetPlayerForTeamSwitch(int source_team_index,
	int destination_team_index, bool is_bot)
{
	if (MUTATOR_CALLHOOK(TeamBalance_GetPlayerForTeamSwitch, source_team_index,
		destination_team_index, is_bot))
	{
		return M_ARGV(3, entity);
	}
	entity lowest_player = NULL;
	float lowest_score = FLOAT_MAX;
	FOREACH_CLIENT(Entity_GetTeamIndex(it) == source_team_index,
	{
		if (IS_BOT_CLIENT(it) != is_bot)
		{
			continue;
		}
		float temp_score = PlayerScore_Get(it, SP_SCORE);
		if (temp_score >= lowest_score)
		{
			continue;
		}
		//PrintToChatAll(sprintf(
		//	"Found %s with lowest score, checking allowed teams", it.netname));
		entity balance = TeamBalance_CheckAllowedTeams(it);
		if (TeamBalance_IsTeamAllowed(balance, source_team_index))
		{
			//PrintToChatAll("Allowed");
			lowest_player = it;
			lowest_score = temp_score;
		}
		else
		{
			//PrintToChatAll("Not allowed");
		}
		TeamBalance_Destroy(balance);
	});
	return lowest_player;
}

void LogTeamChange(float player_id, float team_number, int type)
{
	if (!autocvar_sv_eventlog)
	{
		return;
	}
	if (player_id < 1)
	{
		return;
	}
	GameLogEcho(sprintf(":team:%d:%d:%d", player_id, team_number, type));
}

bool TeamBalance_IsTeamAllowedInternal(entity balance, int index)
{
	return index <= AVAILABLE_TEAMS
	       && balance.m_team_balance_team[index - 1].m_num_players != TEAM_NOT_ALLOWED;
}

void TeamBalance_BanTeamsExcept(entity balance, int index)
{
	for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
	{
		if (i != index)
		{
			balance.m_team_balance_team[i - 1].m_num_players = TEAM_NOT_ALLOWED;
		}
	}
}

entity TeamBalance_GetTeamFromIndex(entity balance, int index)
{
	if (!Team_IsValidIndex(index))
	{
		LOG_FATALF("Index is invalid: %f", index);
	}
	return balance.m_team_balance_team[index - 1];
}

entity TeamBalance_GetTeam(entity balance, int team_num)
{
	return TeamBalance_GetTeamFromIndex(balance, Team_TeamToIndex(team_num));
}

bool TeamBalanceTeam_IsAllowed(entity team_ent)
{
	return team_ent && team_ent.m_num_players != TEAM_NOT_ALLOWED;
}

int TeamBalanceTeam_GetNumberOfPlayers(entity team_ent)
{
	return team_ent.m_num_players;
}

int TeamBalanceTeam_GetNumberOfBots(entity team_ent)
{
	return team_ent.m_num_bots;
}

int TeamBalance_CompareTeamsInternal(entity team_a, entity team_b, entity client, bool use_score)
{
	if (team_a == team_b)
		return TEAMS_COMPARE_EQUAL;

	int team_a_size = IS_REAL_CLIENT(client) ? team_a.m_num_players_net : team_a.m_num_players;
	int team_b_size = IS_REAL_CLIENT(client) ? team_b.m_num_players_net : team_b.m_num_players;

	if (team_a_size < team_b_size)
		return TEAMS_COMPARE_LESS;
	if (team_a_size > team_b_size)
		return TEAMS_COMPARE_GREATER;
	if (!use_score || !team_a_size)
		return TEAMS_COMPARE_EQUAL;

// Compare skill and score together as team strength.
	// Teams without players have 0 skill_mu but may have a score which must still apply.
	bool use_skill = team_a.m_skill_var && team_b.m_skill_var && autocvar_g_balance_teams_skill
		// z-score, <= threshold SDs means difference isn't significant, formula squared for perf
		&& (((team_a.m_skill_mu - team_b.m_skill_mu)**2) / (team_a.m_skill_var + team_b.m_skill_var) > autocvar_g_balance_teams_skill_significance_threshold**2);
	float team_a_strength = use_skill ? team_a.m_skill_mu : 1;
	float team_b_strength = use_skill ? team_b.m_skill_mu : 1;
	// Early in the match scores are ~random due to too few samples,
	// as the match progresses scores become more reliable indicators of team strength.
	// 0.96875 (31/32): if at halftime one team has score 0 and the other has 2 its skill is multiplied by 1.376,
	// < 1 so that a team with 1 point is stronger than one with 0 (but not by much as sample size is small).
	// Applying full score ratio to one team is equivalent here to applying half of it to each.
	if (!warmup_stage && time > game_starttime)
	{
		float timelimit_sec = autocvar_timelimit > 0 ? autocvar_timelimit * 60 : 20 * 60;
		team_a_strength *= (1 + ((team_a.m_team_score ? team_a.m_team_score : 0.96875) / (team_b.m_team_score ? team_b.m_team_score : 0.96875) - 1)
		                      * min(1, (time - game_starttime) / timelimit_sec)**1.5);
	}

	if (team_a_strength < team_b_strength)
		return TEAMS_COMPARE_LESS;
	if (team_a_strength > team_b_strength)
		return TEAMS_COMPARE_GREATER;
	return TEAMS_COMPARE_EQUAL;
}

void SV_ChangeTeam(entity player, int new_color)
{
	if (!teamplay)
		SetPlayerColors(player, new_color);
}

bool QueueNeeded(entity client, int team_index)
{
	if (!teamplay || warmup_stage || !autocvar_g_balance_teams_queue || autocvar_g_campaign || client.team > 0)
		return false;

	int human_clients = 0;
	FOREACH_CLIENT(IS_REAL_CLIENT(it),
	{
		if (++human_clients > 1)
		{
			if (TeamBalance_AreEqual(client, true))
				return true;
			if (team_index <= 0)
				return false; // auto-select will join a smaller team

			entity balance = TeamBalance_CheckAllowedTeams(client);
			TeamBalance_GetTeamCounts(balance, client);
			if ((Team_IndexToBit(team_index) & TeamBalance_FindBestTeams(balance, client, false)) == 0)
			{
				TeamBalance_Destroy(balance);
				return true;
			}
			TeamBalance_Destroy(balance);
			return false;
		}
	});
	return false;
}
