<commit_before>/**
 * Data searching commands.
 * Pokemon Showdown - http://pokemonshowdown.com/
 *
 * Commands for advanced searching for pokemon, moves, items and learnsets.
 * These commands run on a child process by default.
 *
 * @license MIT
 */

import {QueryProcessManager} from '../../lib/process-manager';
import {Utils} from '../../lib/utils';

interface DexOrGroup {
	abilities: {[k: string]: boolean};
	tiers: {[k: string]: boolean};
	doublesTiers: {[k: string]: boolean};
	colors: {[k: string]: boolean};
	'egg groups': {[k: string]: boolean};
	formes: {[k: string]: boolean};
	gens: {[k: string]: boolean};
	moves: {[k: string]: boolean};
	types: {[k: string]: boolean};
	resists: {[k: string]: boolean};
	weak: {[k: string]: boolean};
	stats: {[k: string]: {[k in Direction]: number}};
	skip: boolean;
}

interface MoveOrGroup {
	types: {[k: string]: boolean};
	categories: {[k: string]: boolean};
	contestTypes: {[k: string]: boolean};
	flags: {[k: string]: boolean};
	gens: {[k: string]: boolean};
	recovery: {[k: string]: boolean};
	mon: {[k: string]: boolean};
	property: {[k: string]: {[k in Direction]: number}};
	boost: {[k: string]: boolean};
	lower: {[k: string]: boolean};
	zboost: {[k: string]: boolean};
	status: {[k: string]: boolean};
	volatileStatus: {[k: string]: boolean};
	targets: {[k: string]: boolean};
	recoil: boolean;
	skip: boolean;
}

type Direction = 'less' | 'greater' | 'equal';

const MAX_PROCESSES = 1;
const RESULTS_MAX_LENGTH = 10;

function escapeHTML(str?: string) {
	if (!str) return '';
	return ('' + str)
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&apos;')
		.replace(/\//g, '&#x2f;');
}

export const commands: ChatCommands = {
	ds: 'dexsearch',
	ds1: 'dexsearch',
	ds2: 'dexsearch',
	ds3: 'dexsearch',
	ds4: 'dexsearch',
	ds5: 'dexsearch',
	ds6: 'dexsearch',
	ds7: 'dexsearch',
	ds8: 'dexsearch',
	dsearch: 'dexsearch',
	nds: 'dexsearch',
	dexsearch(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast()) return;
		if (!target) return this.parse('/help dexsearch');
		const targetGen = parseInt(cmd[cmd.length - 1]);
		if (targetGen) target += `, maxgen${targetGen}`;
		if (targetGen && targetGen === 5) {
			const targArray = target.split(',');
			for (const [i, arg] of targArray.entries()) {
				if (arg.includes('|')) {
					const orArray = arg.split('|');
					for (const [j, a] of orArray.entries()) {
						if (toID(a) === 'pu') {
							orArray.splice(j, 1);
							orArray.push('untiered');
							continue;
						}
					}
					targArray[i] = orArray.join('|');
				} else {
					if (toID(arg) === 'pu') {
						targArray.splice(i, 1);
						targArray.push('untiered');
					}
				}
			}
			target = targArray.join(',');
		}
		if (cmd === 'nds') target += ', natdex';
		return runSearch({
			tar: target,
			cmd: 'dexsearch',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				if (targetGen) response.dt += `, gen${targetGen}`;
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},

	dexsearchhelp() {
		this.sendReplyBox(
			`<code>/dexsearch [parameter], [parameter], [parameter], ...</code>: searches for Pok\u00e9mon that fulfill the selected criteria<br/>` +
			`Search categories are: type, tier, color, moves, ability, gen, resists, recovery, zrecovery, priority, stat, weight, height, egg group.<br/>` +
			`Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black.<br/>` +
			`Valid tiers are: Uber/OU/UUBL/UU/RUBL/RU/NUBL/NU/PUBL/PU/ZU/NFE/LC Uber/LC/CAP/CAP NFE/CAP LC.<br/>` +
			`Valid doubles tiers are: DUber/DOU/DBL/DUU/DNU.<br/>` +
			`Types can be searched for by either having the type precede <code>type</code> or just using the type itself as a parameter; e.g., both <code>fire type</code> and <code>fire</code> show all Fire types; however, using <code>psychic</code> as a parameter will show all Pok\u00e9mon that learn the move Psychic and not Psychic types.<br/>` +
			`<code>resists</code> followed by a type will show Pok\u00e9mon that resist that typing (e.g. <code>resists normal</code>).<br/>` +
			`<code>weak</code> followed by a type will show Pok\u00e9mon that are weak to that typing (e.g. <code>weak fire</code>).<br/>` +
			`<code>asc</code> or <code>desc</code> following a stat will show the Pok\u00e9mon in ascending or descending order of that stat respectively (e.g. <code>speed asc</code>).<br/>` +
			`Inequality ranges use the characters <code>>=</code> for <code>≥</code> and <code><=</code> for <code>≤</code>; e.g., <code>hp <= 95</code> searches all Pok\u00e9mon with HP less than or equal to 95.<br/>` +
			`Parameters can be excluded through the use of <code>!</code>; e.g., <code>!water type</code> excludes all Water types.<br/>` +
			`The parameter <code>mega</code> can be added to search for Mega Evolutions only, the parameter <code>gmax</code> can be added to search for Pokemon capable of Gigantamaxing only, and the parameter <code>Fully Evolved</code> (or <code>FE</code>) can be added to search for fully-evolved Pok\u00e9mon.<br/>` +
			`<code>Alola</code>, <code>Galar</code>, <code>Therian</code>, <code>Totem</code>, or <code>Primal</code> can be used as parameters to search for those formes.<br/>` +
			`Parameters separated with <code>|</code> will be searched as alternatives for each other; e.g., <code>trick | switcheroo</code> searches for all Pok\u00e9mon that learn either Trick or Switcheroo.<br/>` +
			`You can search for info in a specific generation by appending the generation to ds; e.g. <code>/ds1 normal</code> searches for all Pok\u00e9mon that were Normal type in Generation I.<br/>` +
			`<code>/dexsearch</code> will search the Galar Pokedex; you can search the National Pokedex by using <code>/nds</code> or by adding <code>natdex</code> as a parameter.<br/>` +
			`Searching for a Pok\u00e9mon with both egg group and type parameters can be differentiated by adding the suffix <code>group</code> onto the egg group parameter; e.g., seaching for <code>grass, grass group</code> will show all Grass types in the Grass egg group.<br/>` +
			`The parameter <code>monotype</code> will only show Pok\u00e9mon that are single-typed.<br/>` +
			`The order of the parameters does not matter.<br/>`
		);
	},

	rollmove: 'randommove',
	randmove: 'randommove',
	randommove(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast(true)) return;
		const targets = target.split(",");
		const targetsBuffer = [];
		let qty;
		for (const arg of targets) {
			if (!arg) continue;
			const num = Number(arg);
			if (Number.isInteger(num)) {
				if (qty) return this.errorReply("Only specify the number of Pok\u00e9mon Moves once.");
				qty = num;
				if (qty < 1 || 15 < qty) return this.errorReply("Number of random Pok\u00e9mon Moves must be between 1 and 15.");
				targetsBuffer.push(`random${qty}`);
			} else {
				targetsBuffer.push(arg);
			}
		}
		if (!qty) targetsBuffer.push("random1");

		return runSearch({
			tar: targetsBuffer.join(","),
			cmd: 'randmove',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast(true)) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	randommovehelp: [
		`/randommove - Generates random Pok\u00e9mon Moves based on given search conditions.`,
		`/randommove uses the same parameters as /movesearch (see '/help ms').`,
		`Adding a number as a parameter returns that many random Pok\u00e9mon Moves, e.g., '/randmove 6' returns 6 random Pok\u00e9mon Moves.`,
	],
	rollpokemon: 'randompokemon',
	randpoke: 'randompokemon',
	randompokemon(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast(true)) return;
		const targets = target.split(",");
		const targetsBuffer = [];
		let qty;
		for (const arg of targets) {
			if (!arg) continue;
			const num = Number(arg);
			if (Number.isInteger(num)) {
				if (qty) return this.errorReply("Only specify the number of Pok\u00e9mon once.");
				qty = num;
				if (qty < 1 || 15 < qty) return this.errorReply("Number of random Pok\u00e9mon must be between 1 and 15.");
				targetsBuffer.push(`random${qty}`);
			} else {
				targetsBuffer.push(arg);
			}
		}
		if (!qty) targetsBuffer.push("random1");

		return runSearch({
			tar: targetsBuffer.join(","),
			cmd: 'randpoke',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast(true)) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	randompokemonhelp: [
		`/randompokemon - Generates random Pok\u00e9mon based on given search conditions.`,
		`/randompokemon uses the same parameters as /dexsearch (see '/help ds').`,
		`Adding a number as a parameter returns that many random Pok\u00e9mon, e.g., '/randpoke 6' returns 6 random Pok\u00e9mon.`,
	],

	ms: 'movesearch',
	ms1: 'movesearch',
	ms2: 'movesearch',
	ms3: 'movesearch',
	ms4: 'movesearch',
	ms5: 'movesearch',
	ms6: 'movesearch',
	ms7: 'movesearch',
	ms8: 'movesearch',
	msearch: 'movesearch',
	nms: 'movesearch',
	movesearch(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast()) return;
		if (!target) return this.parse('/help movesearch');
		const targetGen = parseInt(cmd[cmd.length - 1]);
		if (targetGen) target += `, maxgen${targetGen}`;
		if (cmd === 'nms') target += ', natdex';
		return runSearch({
			tar: target,
			cmd: 'movesearch',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	movesearchhelp() {
		this.sendReplyBox(
			`<code>/movesearch [parameter], [parameter], [parameter], ...</code>: searches for moves that fulfill the selected criteria.<br/>` +
			`Search categories are: type, category, gen, contest condition, flag, status inflicted, type boosted, Pok\u00e9mon targeted, and numeric range for base power, pp, priority, and accuracy.<br/>` +
			`Types can be followed by <code> type</code> for clarity; e.g., <code>dragon type</code>.<br/>` +
			`Stat boosts must be preceded with <code>boosts </code>, and stat-lowering moves with <code>lowers </code>; e.g., <code>boosts attack</code> searches for moves that boost the Attack stat of either Pok\u00e9mon.<br/>` +
			`Z-stat boosts must be preceded with <code>zboosts </code>; e.g., <code>zboosts accuracy</code> searches for all Status moves with Z-Effects that boost the user's accuracy.<br/>` +
			`Moves that have a Z-Effect of fully restoring the user's health can be searched for with <code>zrecovery</code>.<br/>` +
			`Move targets must be preceded with <code>targets </code>; e.g., <code>targets user</code> searches for moves that target the user.<br/>` +
			`Valid move targets are: one ally, user or ally, one adjacent opponent, all Pokemon, all adjacent Pokemon, all adjacent opponents, user and allies, user's side, user's team, any Pokemon, opponent's side, one adjacent Pokemon, random adjacent Pokemon, scripted, and user.<br/>` +
			`Inequality ranges use the characters <code>></code> and <code><</code>.<br/>` +
			`Parameters can be excluded through the use of <code>!</code>; e.g., <code>!water type</code> excludes all Water-type moves.<br/>` +
			`<code>asc</code> or <code>desc</code> following a move property will arrange the names in ascending or descending order of that property, respectively; e.g., <code>basepower asc</code> will arrange moves in ascending order of their base powers.<br/>` +
			`Valid flags are: authentic (bypasses substitute), bite, bullet, charge, contact, dance, defrost, gravity, mirror (reflected by mirror move), ohko, powder, priority, protect, pulse, punch, recharge, recovery, reflectable, secondary, snatch, sound, and zmove.<br/>` +
			`A search that includes <code>!protect</code> will show all moves that bypass protection.<br/>` +
			`<code>protection</code> as a parameter will search protection moves like Protect, Detect, etc.<br/>` +
			`<code>max</code> or <code>gmax</code> as parameters will search for Max Moves and G-Max moves respectively.<br/>` +
			`Parameters separated with <code>|</code> will be searched as alternatives for each other; e.g., <code>fire | water</code> searches for all moves that are either Fire type or Water type.<br/>` +
			`If a Pok\u00e9mon is included as a parameter, only moves from its movepool will be included in the search.<br/>` +
			`You can search for info in a specific generation by appending the generation to ms; e.g. <code>ms1 normal</code> searches for all moves that were Normal type in Generation I.<br/>` +
			`<code>/ms</code> will search the Galar Moves; you can search the National Moves by using <code>/nms</code> or by adding <code>natdex</code> as a parameter.<br/>` +
			`The order of the parameters does not matter.`
		);
	},

	isearch: 'itemsearch',
	is: 'itemsearch',
	is2: 'itemsearch',
	is3: 'itemsearch',
	is4: 'itemsearch',
	is5: 'itemsearch',
	is6: 'itemsearch',
	is7: 'itemsearch',
	is8: 'itemsearch',
	itemsearch(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast()) return;
		if (!target) return this.parse('/help itemsearch');
		const targetGen = parseInt(cmd[cmd.length - 1]);
		if (targetGen) target += ` maxgen${targetGen}`;

		return runSearch({
			tar: target,
			cmd: 'itemsearch',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	itemsearchhelp() {
		this.sendReplyBox(
			`<code>/itemsearch [item description]</code>: finds items that match the given keywords.<br/>` +
			`This command accepts natural language. (tip: fewer words tend to work better)<br/>` +
			`The <code>gen</code> keyword can be used to search for items introduced in a given generation; e.g., <code>/is gen4</code> searches for items introduced in Generation 4.<br/>` +
			`To search for items within a generation, append the generation to <code>/is</code> or use the <code>maxgen</code> keyword; e.g., <code>/is4 Water-type</code> or <code>/is maxgen4 Water-type</code> searches for items whose Generation 4 description includes "Water-type".<br/>` +
			`Searches with <code>fling</code> in them will find items with the specified Fling behavior.<br/>` +
			`Searches with <code>natural gift</code> in them will find items with the specified Natural Gift behavior.`
		);
	},

	asearch: 'abilitysearch',
	as: 'abilitysearch',
	as3: 'abilitysearch',
	as4: 'abilitysearch',
	as5: 'abilitysearch',
	as6: 'abilitysearch',
	as7: 'abilitysearch',
	as8: 'abilitysearch',
	abilitysearch(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast()) return;
		if (!target) return this.parse('/help abilitysearch');
		const targetGen = parseInt(cmd[cmd.length - 1]);
		if (targetGen) target += ` maxgen${targetGen}`;

		return runSearch({
			tar: target,
			cmd: 'abilitysearch',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	abilitysearchhelp() {
		this.sendReplyBox(
			`<code>/abilitysearch [ability description]</code>: finds abilities that match the given keywords.<br/>` +
			`This command accepts natural language. (tip: fewer words tend to work better)<br/>` +
			`The <code>gen</code> keyword can be used to search for abilities introduced in a given generation; e.g., <code>/as gen4</code> searches for abilities introduced in Generation 4.<br/>` +
			`To search for abilities within a generation, append the generation to <code>/as</code> or use the <code>maxgen</code> keyword; e.g., <code>/as4 Water-type</code> or <code>/as maxgen4 Water-type</code> searches for abilities whose Generation 4 description includes "Water-type".`
		);
	},

	learnset: 'learn',
	learnall: 'learn',
	learn5: 'learn',
	rbylearn: 'learn',
	gsclearn: 'learn',
	advlearn: 'learn',
	dpplearn: 'learn',
	bw2learn: 'learn',
	oraslearn: 'learn',
	usumlearn: 'learn',
	learn(target, room, user, connection, cmd, message) {
		if (!target) return this.parse('/help learn');
		if (!this.canBroadcast()) return;

		return runSearch({
			tar: target,
			cmd: 'learn',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: cmd,
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			}
			this.update();
		});
	},
	learnhelp: [
		`/learn [ruleset], [pokemon], [move, move, ...] - Displays how the Pok\u00e9mon can learn the given moves, if it can at all.`,
		`!learn [ruleset], [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ # &`,
		`Specifying a ruleset is entirely optional. The ruleset can be a format, a generation (e.g.: gen3) or 'pentagon'. A value of 'pentagon' indicates that trading from previous generations is not allowed.`,
		`/learn5 displays how the Pok\u00e9mon can learn the given moves at level 5, if it can at all.`,
		`/learnall displays all of the possible fathers for egg moves.`,
		`/learn can also be prefixed by a generation acronym (e.g.: /dpplearn) to indicate which generation is used. Valid options are: rby gsc adv dpp bw2 oras usum`,
	],
};

function runDexsearch(target: string, cmd: string, canAll: boolean, message: string) {
	const searches: DexOrGroup[] = [];
	const allTiers: {[k: string]: TierTypes.Singles | TierTypes.Other} = Object.assign(Object.create(null), {
		uber: 'Uber', ubers: 'Uber', ou: 'OU',
		uubl: 'UUBL', uu: 'UU',
		rubl: 'RUBL', ru: 'RU',
		nubl: 'NUBL', nu: 'NU', untiered: '(NU)',
		publ: 'PUBL', pu: 'PU', zu: '(PU)',
		nfe: 'NFE',
		lcuber: 'LC Uber', lcubers: 'LC Uber', lc: 'LC',
		cap: 'CAP', caplc: 'CAP LC', capnfe: 'CAP NFE',
	});
	const allDoublesTiers: {[k: string]: TierTypes.Singles | TierTypes.Other} = Object.assign(Object.create(null), {
		doublesubers: 'DUber', doublesuber: 'DUber', duber: 'DUber', dubers: 'DUber',
		doublesou: 'DOU', dou: 'DOU',
		doublesbl: 'DBL', dbl: 'DBL',
		doublesuu: 'DUU', duu: 'DUU',
		doublesnu: '(DUU)', dnu: '(DUU)',
	});
	const allTypes = Object.create(null);
	for (const i in Dex.data.TypeChart) {
		allTypes[toID(i)] = i;
	}
	const allColors = ['green', 'red', 'blue', 'white', 'brown', 'yellow', 'purple', 'pink', 'gray', 'black'];
	const allEggGroups: {[k: string]: string} = Object.assign(Object.create(null), {
		amorphous: 'Amorphous',
		bug: 'Bug',
		ditto: 'Ditto',
		dragon: 'Dragon',
		fairy: 'Fairy',
		field: 'Field',
		flying: 'Flying',
		grass: 'Grass',
		humanlike: 'Human-Like',
		mineral: 'Mineral',
		monster: 'Monster',
		undiscovered: 'Undiscovered',
		water1: 'Water 1',
		water2: 'Water 2',
		water3: 'Water 3',
	});
	const allFormes = ['alola', 'galar', 'primal', 'therian', 'totem'];
	const allStats = ['hp', 'atk', 'def', 'spa', 'spd', 'spe', 'bst', 'weight', 'height', 'gen'];
	const allStatAliases: {[k: string]: string} = {
		attack: 'atk', defense: 'def', specialattack: 'spa', spc: 'spa', special: 'spa', spatk: 'spa',
		specialdefense: 'spd', spdef: 'spd', speed: 'spe', wt: 'weight', ht: 'height', generation: 'gen',
	};
	let showAll = false;
	let sort = null;
	let megaSearch = null;
	let gmaxSearch = null;
	let tierSearch = null;
	let capSearch = null;
	let nationalSearch = null;
	let fullyEvolvedSearch = null;
	let singleTypeSearch = false;
	let randomOutput = 0;
	let maxGen = 0;
	const validParameter = (cat: string, param: string, isNotSearch: boolean, input: string) => {
		const uniqueTraits = ['colors', 'gens'];
		for (const group of searches) {
			const g = group[cat as keyof DexOrGroup];
			if (g === undefined) continue;
			if (typeof g !== 'boolean' && g[param] === undefined) {
				if (uniqueTraits.includes(cat)) {
					for (const currentParam in g) {
						if (g[currentParam] !== isNotSearch && !isNotSearch) return `A Pok&eacute;mon cannot have multiple ${cat}.`;
					}
				}
				continue;
			}
			if (typeof g !== 'boolean' && g[param] === isNotSearch) {
				return `A search cannot both include and exclude '${input}'.`;
			} else {
				return `The search included '${(isNotSearch ? "!" : "") + input}' more than once.`;
			}
		}
		return false;
	};

	for (const andGroup of target.split(',')) {
		const orGroup: DexOrGroup = {
			abilities: {}, tiers: {}, doublesTiers: {}, colors: {}, 'egg groups': {}, formes: {},
			gens: {}, moves: {}, types: {}, resists: {}, weak: {}, stats: {}, skip: false,
		};
		const parameters = andGroup.split("|");
		if (parameters.length > 3) return {error: "No more than 3 alternatives for each parameter may be used."};
		for (const parameter of parameters) {
			let isNotSearch = false;
			target = parameter.trim().toLowerCase();
			if (target.charAt(0) === '!') {
				isNotSearch = true;
				target = target.substr(1);
			}

			const targetAbility = Dex.getAbility(target);
			if (targetAbility.exists) {
				const invalid = validParameter("abilities", targetAbility.id, isNotSearch, targetAbility.name);
				if (invalid) return {error: invalid};
				orGroup.abilities[targetAbility.name] = !isNotSearch;
				continue;
			}

			if (toID(target) in allTiers) {
				target = allTiers[toID(target)];
				if (target.startsWith("CAP")) {
					if (capSearch === isNotSearch) return {error: "A search cannot both include and exclude CAP tiers."};
					capSearch = !isNotSearch;
				}
				const invalid = validParameter("tiers", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				tierSearch = tierSearch || !isNotSearch;
				orGroup.tiers[target] = !isNotSearch;
				continue;
			}

			if (toID(target) in allDoublesTiers) {
				target = allDoublesTiers[toID(target)];
				const invalid = validParameter("doubles tiers", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				tierSearch = tierSearch || !isNotSearch;
				orGroup.doublesTiers[target] = !isNotSearch;
				continue;
			}

			if (allColors.includes(target)) {
				target = target.charAt(0).toUpperCase() + target.slice(1);
				const invalid = validParameter("colors", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				orGroup.colors[target] = !isNotSearch;
				continue;
			}

			const targetMove = Dex.getMove(target);
			if (targetMove.exists) {
				const invalid = validParameter("moves", targetMove.id, isNotSearch, target);
				if (invalid) return {error: invalid};
				orGroup.moves[targetMove.id] = !isNotSearch;
				continue;
			}

			let targetType;
			if (target.endsWith('type')) {
				targetType = toID(target.substring(0, target.indexOf('type')));
			} else {
				targetType = toID(target);
			}
			if (targetType in allTypes) {
				target = allTypes[targetType];
				const invalid = validParameter("types", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				if ((orGroup.types[target] && isNotSearch) || (orGroup.types[target] === false && !isNotSearch)) {
					return {error: 'A search cannot both exclude and include a type.'};
				}
				orGroup.types[target] = !isNotSearch;
				continue;
			}

			if (['mono', 'monotype'].includes(toID(target))) {
				singleTypeSearch = true;
				orGroup.skip = true;
				continue;
			}

			if (target.substr(0, 6) === 'maxgen') {
				maxGen = parseInt(target[6]);
				if (!maxGen || maxGen < 1 || maxGen > 8) return {error: "The generation must be between 1 and 8"};
				orGroup.skip = true;
				continue;
			}

			if (target === 'natdex') {
				nationalSearch = true;
				orGroup.skip = true;
				continue;
			}

			let groupIndex = target.indexOf('group');
			if (groupIndex === -1) groupIndex = target.length;
			if (groupIndex !== target.length || toID(target) in allEggGroups) {
				target = toID(target.substring(0, groupIndex));
				if (target in allEggGroups) {
					target = allEggGroups[toID(target)];
					const invalid = validParameter("egg groups", target, isNotSearch, target);
					if (invalid) return {error: invalid};
					orGroup['egg groups'][target] = !isNotSearch;
					continue;
				} else {
					return {error: `'${target}' is not a recognized egg group.`};
				}
			}
			if (toID(target) in allEggGroups) {
				target = allEggGroups[toID(target)];
				const invalid = validParameter("egg groups", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				orGroup['egg groups'][target] = !isNotSearch;
				continue;
			}

			let targetInt = 0;
			if (target.substr(0, 1) === 'g' && Number.isInteger(parseFloat(target.substr(1)))) {
				targetInt = parseInt(target.substr(1).trim());
			} else if (target.substr(0, 3) === 'gen' && Number.isInteger(parseFloat(target.substr(3)))) {
				targetInt = parseInt(target.substr(3).trim());
			}
			if (0 < targetInt && targetInt < 9) {
				const invalid = validParameter("gens", String(targetInt), isNotSearch, target);
				if (invalid) return {error: invalid};
				orGroup.gens[targetInt] = !isNotSearch;
				continue;
			}

			if (target.endsWith(' asc') || target.endsWith(' desc')) {
				if (parameters.length > 1) return {error: `The parameter '${target.split(' ')[1]}' cannot have alternative parameters`};
				const stat = allStatAliases[toID(target.split(' ')[0])] || toID(target.split(' ')[0]);
				if (!allStats.includes(stat)) return {error: `'${escapeHTML(target)}' did not contain a valid stat.`};
				sort = `${stat}${target.endsWith(' asc') ? '+' : '-'}`;
				orGroup.skip = true;
				break;
			}

			if (target === 'all') {
				if (!canAll) return {error: "A search with the parameter 'all' cannot be broadcast."};
				if (parameters.length > 1) return {error: "The parameter 'all' cannot have alternative parameters"};
				showAll = true;
				orGroup.skip = true;
				break;
			}

			if (target.substr(0, 6) === 'random' && cmd === 'randpoke') {
				// Validation for this is in the /randpoke command
				randomOutput = parseInt(target.substr(6));
				orGroup.skip = true;
				continue;
			}

			if (allFormes.includes(toID(target))) {
				target = toID(target);
				orGroup.formes[target] = !isNotSearch;
				continue;
			}

			if (target === 'megas' || target === 'mega') {
				if (megaSearch === isNotSearch) return {error: "A search cannot include and exclude 'mega'."};
				if (parameters.length > 1) return {error: "The parameter 'mega' cannot have alternative parameters"};
				megaSearch = !isNotSearch;
				orGroup.skip = true;
				break;
			}

			if (target === 'gmax' || target === 'gigantamax') {
				if (gmaxSearch === isNotSearch) return {error: "A search cannot include and exclude 'gigantamax'."};
				if (parameters.length > 1) return {error: "The parameter 'gigantamax' cannot have alternative parameters"};
				gmaxSearch = !isNotSearch;
				orGroup.skip = true;
				break;
			}

			if (['fully evolved', 'fullyevolved', 'fe'].includes(target)) {
				if (fullyEvolvedSearch === isNotSearch) return {error: "A search cannot include and exclude 'fully evolved'."};
				if (parameters.length > 1) return {error: "The parameter 'fully evolved' cannot have alternative parameters"};
				fullyEvolvedSearch = !isNotSearch;
				orGroup.skip = true;
				break;
			}

			if (target === 'recovery') {
				if (parameters.length > 1) return {error: "The parameter 'recovery' cannot have alternative parameters"};
				const recoveryMoves = [
					"recover", "roost", "moonlight", "morningsun", "synthesis", "milkdrink",
					"slackoff", "softboiled", "wish", "healorder", "shoreup", "lifedew",
				];
				for (const move of recoveryMoves) {
					const invalid = validParameter("moves", move, isNotSearch, target);
					if (invalid) return {error: invalid};
					if (isNotSearch) {
						const bufferObj: {moves: {[k: string]: boolean}} = {moves: {}};
						bufferObj.moves[move] = false;
						searches.push(bufferObj as DexOrGroup);
					} else {
						orGroup.moves[move] = true;
					}
				}
				if (isNotSearch) orGroup.skip = true;
				break;
			}

			if (target === 'zrecovery') {
				if (parameters.length > 1) return {error: "The parameter 'zrecovery' cannot have alternative parameters"};
				const recoveryMoves = [
					"aromatherapy", "bellydrum", "conversion2", "haze", "healbell", "mist",
					"psychup", "refresh", "spite", "stockpile", "teleport", "transform",
				];
				for (const moveid of recoveryMoves) {
					const invalid = validParameter("moves", moveid, isNotSearch, target);
					if (invalid) return {error: invalid};
					if (isNotSearch) {
						const bufferObj: {moves: {[k: string]: boolean}} = {moves: {}};
						bufferObj.moves[moveid] = false;
						searches.push(bufferObj as DexOrGroup);
					} else {
						orGroup.moves[moveid] = true;
					}
				}
				if (isNotSearch) orGroup.skip = true;
				break;
			}

			if (target === 'priority') {
				if (parameters.length > 1) return {error: "The parameter 'priority' cannot have alternative parameters"};
				for (const move in Dex.data.Moves) {
					const moveData = Dex.getMove(move);
					if (moveData.category === "Status" || moveData.id === "bide") continue;
					if (moveData.priority > 0) {
						const invalid = validParameter("moves", move, isNotSearch, target);
						if (invalid) return {error: invalid};
						if (isNotSearch) {
							const bufferObj: {moves: {[k: string]: boolean}} = {moves: {}};
							bufferObj.moves[move] = false;
							searches.push(bufferObj as DexOrGroup);
						} else {
							orGroup.moves[move] = true;
						}
					}
				}
				if (isNotSearch) orGroup.skip = true;
				break;
			}

			if (target.substr(0, 8) === 'resists ') {
				const targetResist = target.substr(8, 1).toUpperCase() + target.substr(9);
				if (targetResist in Dex.data.TypeChart) {
					const invalid = validParameter("resists", targetResist, isNotSearch, target);
					if (invalid) return {error: invalid};
					orGroup.resists[targetResist] = !isNotSearch;
					continue;
				} else {
					return {error: `'${targetResist}' is not a recognized type.`};
				}
			}

			if (target.substr(0, 5) === 'weak ') {
				const targetWeak = target.substr(5, 1).toUpperCase() + target.substr(6);
				if (targetWeak in Dex.data.TypeChart) {
					const invalid = validParameter("weak", targetWeak, isNotSearch, target);
					if (invalid) return {error: invalid};
					orGroup.weak[targetWeak] = !isNotSearch;
					continue;
				} else {
					return {error: `'${targetWeak}' is not a recognized type.`};
				}
			}

			const inequality = target.search(/>|<|=/);
			let inequalityString;
			if (inequality >= 0) {
				if (isNotSearch) return {error: "You cannot use the negation symbol '!' in stat ranges."};
				if (target.charAt(inequality + 1) === '=') {
					inequalityString = target.substr(inequality, 2);
				} else {
					inequalityString = target.charAt(inequality);
				}
				const targetParts = target.replace(/\s/g, '').split(inequalityString);
				let num;
				let stat;
				const directions: Direction[] = [];
				if (!isNaN(parseFloat(targetParts[0]))) {
					// e.g. 100 < spe
					num = parseFloat(targetParts[0]);
					stat = targetParts[1];
					if (inequalityString[0] === '>') directions.push('less');
					if (inequalityString[0] === '<') directions.push('greater');
				} else if (!isNaN(parseFloat(targetParts[1]))) {
					// e.g. spe > 100
					num = parseFloat(targetParts[1]);
					stat = targetParts[0];
					if (inequalityString[0] === '<') directions.push('less');
					if (inequalityString[0] === '>') directions.push('greater');
				} else {
					return {error: `No value given to compare with '${escapeHTML(target)}'.`};
				}
				if (inequalityString.slice(-1) === '=') directions.push('equal');
				if (stat in allStatAliases) stat = allStatAliases[stat];
				if (!allStats.includes(stat)) return {error: `'${escapeHTML(target)}' did not contain a valid stat.`};
				if (!orGroup.stats[stat]) orGroup.stats[stat] = Object.create(null);
				for (const direction of directions) {
					if (orGroup.stats[stat][direction]) return {error: `Invalid stat range for ${stat}.`};
					orGroup.stats[stat][direction] = num;
				}
				continue;
			}
			return {error: `'${escapeHTML(target)}' could not be found in any of the search categories.`};
		}
		if (!orGroup.skip) {
			searches.push(orGroup);
		}
	}
	if (
		showAll && searches.length === 0 && !maxGen && !singleTypeSearch &&
		megaSearch === null && gmaxSearch === null && fullyEvolvedSearch === null && sort === null
	) {
		return {
			error: "No search parameters other than 'all' were found. Try '/help dexsearch' for more information on this command.",
		};
	}

	if (!maxGen) maxGen = 8;
	const mod = Dex.mod('gen' + maxGen);
	const dex: {[k: string]: Species} = {};
	for (const pokemon in mod.data.Pokedex) {
		const species = mod.getSpecies(pokemon);
		const megaSearchResult = (
			megaSearch === null || (megaSearch === true && species.isMega) ||
			(megaSearch === false && !species.isMega)
		);
		const gmaxSearchResult = (
			gmaxSearch === null || (gmaxSearch === true && species.name.endsWith('-Gmax')) ||
			(gmaxSearch === false && !species.name.endsWith('-Gmax'))
		);
		const fullyEvolvedSearchResult = (
			fullyEvolvedSearch === null ||
			(fullyEvolvedSearch === true && !species.nfe) ||
			(fullyEvolvedSearch === false && species.nfe)
		);
		if (
			species.gen <= maxGen &&
			(
				(
					nationalSearch &&
					species.isNonstandard &&
					!["Custom", "Glitch", "Pokestar"].includes(species.isNonstandard)
				) ||
				(species.tier !== 'Unreleased' && species.tier !== 'Illegal')
			) &&
			(!species.tier.startsWith("CAP") || capSearch) &&
			megaSearchResult &&
			gmaxSearchResult &&
			fullyEvolvedSearchResult
		) {
			dex[pokemon] = species;
		}
	}

	// Prioritize searches with the least alternatives.
	const accumulateKeyCount = (count: number, searchData: AnyObject) =>
		count + (typeof searchData === 'object' ? Object.keys(searchData).length : 0);
	searches.sort(
		(a, b) => Object.values(a).reduce(accumulateKeyCount, 0) - Object.values(b).reduce(accumulateKeyCount, 0)
	);

	for (const alts of searches) {
		if (alts.skip) continue;
		for (const mon in dex) {
			let matched = false;
			if (alts.gens && Object.keys(alts.gens).length) {
				if (alts.gens[dex[mon].gen]) continue;
				if (Object.values(alts.gens).includes(false) && alts.gens[dex[mon].gen] !== false) continue;
			}

			if (alts.colors && Object.keys(alts.colors).length) {
				if (alts.colors[dex[mon].color]) continue;
				if (Object.values(alts.colors).includes(false) && alts.colors[dex[mon].color] !== false) continue;
			}

			for (const eggGroup in alts['egg groups']) {
				if (dex[mon].eggGroups.includes(eggGroup) === alts['egg groups'][eggGroup]) {
					matched = true;
					break;
				}
			}

			if (alts.tiers && Object.keys(alts.tiers).length) {
				let tier = dex[mon].tier;
				if (tier[0] === '(' && tier !== '(PU)' && tier !== '(NU)') tier = tier.slice(1, -1) as TierTypes.Singles;
				// if (tier === 'New') tier = 'OU';
				if (alts.tiers[tier]) continue;
				if (Object.values(alts.tiers).includes(false) && alts.tiers[tier] !== false) continue;
				// LC handling, checks for LC Pokemon in higher tiers that need to be handled separately,
				// as well as event-only Pokemon that are not eligible for LC despite being the first stage
				let format = Dex.getFormat('gen' + maxGen + 'lc');
				if (!format.exists) format = Dex.getFormat('gen8lc');
				if (
					alts.tiers.LC &&
					!dex[mon].prevo &&
					dex[mon].evos.some(evo => mod.getSpecies(evo).gen <= mod.gen) &&
					!format.banlist.includes(dex[mon].name) &&
					!format.banlist.includes(dex[mon].name + "-Base")
				) {
					const lsetData = Dex.getLearnsetData(dex[mon].id);
					if (lsetData.exists && lsetData.eventData && lsetData.eventOnly) {
						let validEvents = 0;
						for (const event of lsetData.eventData) {
							if (event.level && event.level <= 5) validEvents++;
						}
						if (validEvents > 0) continue;
					} else {
						continue;
					}
				}
			}

			if (alts.doublesTiers && Object.keys(alts.doublesTiers).length) {
				let tier = dex[mon].doublesTier;
				if (tier && tier[0] === '(' && tier !== '(DUU)') tier = tier.slice(1, -1) as TierTypes.Doubles;
				if (alts.doublesTiers[tier]) continue;
				if (Object.values(alts.doublesTiers).includes(false) && alts.doublesTiers[tier] !== false) continue;
			}

			for (const type in alts.types) {
				if (dex[mon].types.includes(type) === alts.types[type]) {
					matched = true;
					break;
				}
			}
			if (matched) continue;

			for (const type in alts.resists) {
				let effectiveness = 0;
				const notImmune = mod.getImmunity(type, dex[mon]);
				if (notImmune) effectiveness = mod.getEffectiveness(type, dex[mon]);
				if (!alts.resists[type]) {
					if (notImmune && effectiveness >= 0) matched = true;
				} else {
					if (!notImmune || effectiveness < 0) matched = true;
				}
			}
			if (matched) continue;

			for (const type in alts.weak) {
				let effectiveness = 0;
				const notImmune = mod.getImmunity(type, dex[mon]);
				if (notImmune) effectiveness = mod.getEffectiveness(type, dex[mon]);
				if (alts.weak[type]) {
					if (notImmune && effectiveness >= 1) matched = true;
				} else {
					if (!notImmune || effectiveness < 1) matched = true;
				}
			}
			if (matched) continue;

			for (const ability in alts.abilities) {
				if (Object.values(dex[mon].abilities).includes(ability) === alts.abilities[ability]) {
					matched = true;
					break;
				}
			}
			if (matched) continue;

			for (const forme in alts.formes) {
				if (toID(dex[mon].forme).includes(forme) === alts.formes[forme]) {
					matched = true;
					break;
				}
			}
			if (matched) continue;

			for (const stat in alts.stats) {
				let monStat = 0;
				if (stat === 'bst') {
					monStat = dex[mon].bst;
				} else if (stat === 'weight') {
					monStat = dex[mon].weighthg / 10;
				} else if (stat === 'height') {
					monStat = dex[mon].heightm;
				} else if (stat === 'gen') {
					monStat = dex[mon].gen;
				} else {
					monStat = dex[mon].baseStats[stat as StatName];
				}
				if (typeof alts.stats[stat].less === 'number') {
					if (monStat < alts.stats[stat].less) {
						matched = true;
						break;
					}
				}
				if (typeof alts.stats[stat].greater === 'number') {
					if (monStat > alts.stats[stat].greater) {
						matched = true;
						break;
					}
				}
				if (typeof alts.stats[stat].equal === 'number') {
					if (monStat === alts.stats[stat].equal) {
						matched = true;
						break;
					}
				}
			}
			if (matched) continue;

			const validator = TeamValidator.get(nationalSearch ? `gen8nationaldexag` : `gen${maxGen}ou`);
			const pokemonSource = validator.allSources();
			for (const move of Object.keys(alts.moves).map(x => Dex.getMove(x))) {
				if (move.gen <= maxGen && !validator.checkLearnset(move, dex[mon], pokemonSource) === alts.moves[move.id]) {
					matched = true;
					break;
				}
				if (!pokemonSource.size()) break;
			}
			if (matched) continue;

			delete dex[mon];
		}
	}
	let results: string[] = [];
	for (const mon of Object.keys(dex).sort()) {
		if (singleTypeSearch && dex[mon].types.length !== 1) continue;
		const isAlola = dex[mon].forme === "Alola" && dex[mon].name !== "Pikachu-Alola";
		const allowGmax = (gmaxSearch || tierSearch);
		if (!isAlola && dex[mon].baseSpecies && results.includes(dex[mon].baseSpecies)) continue;
		if (dex[mon].name.endsWith('-Gmax') && !allowGmax) continue;<commit_msg>Datasearch: Support excluding monotype Pokemon (#7214)<commit_after>/**
 * Data searching commands.
 * Pokemon Showdown - http://pokemonshowdown.com/
 *
 * Commands for advanced searching for pokemon, moves, items and learnsets.
 * These commands run on a child process by default.
 *
 * @license MIT
 */

import {QueryProcessManager} from '../../lib/process-manager';
import {Utils} from '../../lib/utils';

interface DexOrGroup {
	abilities: {[k: string]: boolean};
	tiers: {[k: string]: boolean};
	doublesTiers: {[k: string]: boolean};
	colors: {[k: string]: boolean};
	'egg groups': {[k: string]: boolean};
	formes: {[k: string]: boolean};
	gens: {[k: string]: boolean};
	moves: {[k: string]: boolean};
	types: {[k: string]: boolean};
	resists: {[k: string]: boolean};
	weak: {[k: string]: boolean};
	stats: {[k: string]: {[k in Direction]: number}};
	skip: boolean;
}

interface MoveOrGroup {
	types: {[k: string]: boolean};
	categories: {[k: string]: boolean};
	contestTypes: {[k: string]: boolean};
	flags: {[k: string]: boolean};
	gens: {[k: string]: boolean};
	recovery: {[k: string]: boolean};
	mon: {[k: string]: boolean};
	property: {[k: string]: {[k in Direction]: number}};
	boost: {[k: string]: boolean};
	lower: {[k: string]: boolean};
	zboost: {[k: string]: boolean};
	status: {[k: string]: boolean};
	volatileStatus: {[k: string]: boolean};
	targets: {[k: string]: boolean};
	recoil: boolean;
	skip: boolean;
}

type Direction = 'less' | 'greater' | 'equal';

const MAX_PROCESSES = 1;
const RESULTS_MAX_LENGTH = 10;

function escapeHTML(str?: string) {
	if (!str) return '';
	return ('' + str)
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&apos;')
		.replace(/\//g, '&#x2f;');
}

export const commands: ChatCommands = {
	ds: 'dexsearch',
	ds1: 'dexsearch',
	ds2: 'dexsearch',
	ds3: 'dexsearch',
	ds4: 'dexsearch',
	ds5: 'dexsearch',
	ds6: 'dexsearch',
	ds7: 'dexsearch',
	ds8: 'dexsearch',
	dsearch: 'dexsearch',
	nds: 'dexsearch',
	dexsearch(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast()) return;
		if (!target) return this.parse('/help dexsearch');
		const targetGen = parseInt(cmd[cmd.length - 1]);
		if (targetGen) target += `, maxgen${targetGen}`;
		if (targetGen && targetGen === 5) {
			const targArray = target.split(',');
			for (const [i, arg] of targArray.entries()) {
				if (arg.includes('|')) {
					const orArray = arg.split('|');
					for (const [j, a] of orArray.entries()) {
						if (toID(a) === 'pu') {
							orArray.splice(j, 1);
							orArray.push('untiered');
							continue;
						}
					}
					targArray[i] = orArray.join('|');
				} else {
					if (toID(arg) === 'pu') {
						targArray.splice(i, 1);
						targArray.push('untiered');
					}
				}
			}
			target = targArray.join(',');
		}
		if (cmd === 'nds') target += ', natdex';
		return runSearch({
			tar: target,
			cmd: 'dexsearch',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				if (targetGen) response.dt += `, gen${targetGen}`;
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},

	dexsearchhelp() {
		this.sendReplyBox(
			`<code>/dexsearch [parameter], [parameter], [parameter], ...</code>: searches for Pok\u00e9mon that fulfill the selected criteria<br/>` +
			`Search categories are: type, tier, color, moves, ability, gen, resists, recovery, zrecovery, priority, stat, weight, height, egg group.<br/>` +
			`Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black.<br/>` +
			`Valid tiers are: Uber/OU/UUBL/UU/RUBL/RU/NUBL/NU/PUBL/PU/ZU/NFE/LC Uber/LC/CAP/CAP NFE/CAP LC.<br/>` +
			`Valid doubles tiers are: DUber/DOU/DBL/DUU/DNU.<br/>` +
			`Types can be searched for by either having the type precede <code>type</code> or just using the type itself as a parameter; e.g., both <code>fire type</code> and <code>fire</code> show all Fire types; however, using <code>psychic</code> as a parameter will show all Pok\u00e9mon that learn the move Psychic and not Psychic types.<br/>` +
			`<code>resists</code> followed by a type will show Pok\u00e9mon that resist that typing (e.g. <code>resists normal</code>).<br/>` +
			`<code>weak</code> followed by a type will show Pok\u00e9mon that are weak to that typing (e.g. <code>weak fire</code>).<br/>` +
			`<code>asc</code> or <code>desc</code> following a stat will show the Pok\u00e9mon in ascending or descending order of that stat respectively (e.g. <code>speed asc</code>).<br/>` +
			`Inequality ranges use the characters <code>>=</code> for <code>≥</code> and <code><=</code> for <code>≤</code>; e.g., <code>hp <= 95</code> searches all Pok\u00e9mon with HP less than or equal to 95.<br/>` +
			`Parameters can be excluded through the use of <code>!</code>; e.g., <code>!water type</code> excludes all Water types.<br/>` +
			`The parameter <code>mega</code> can be added to search for Mega Evolutions only, the parameter <code>gmax</code> can be added to search for Pokemon capable of Gigantamaxing only, and the parameter <code>Fully Evolved</code> (or <code>FE</code>) can be added to search for fully-evolved Pok\u00e9mon.<br/>` +
			`<code>Alola</code>, <code>Galar</code>, <code>Therian</code>, <code>Totem</code>, or <code>Primal</code> can be used as parameters to search for those formes.<br/>` +
			`Parameters separated with <code>|</code> will be searched as alternatives for each other; e.g., <code>trick | switcheroo</code> searches for all Pok\u00e9mon that learn either Trick or Switcheroo.<br/>` +
			`You can search for info in a specific generation by appending the generation to ds; e.g. <code>/ds1 normal</code> searches for all Pok\u00e9mon that were Normal type in Generation I.<br/>` +
			`<code>/dexsearch</code> will search the Galar Pokedex; you can search the National Pokedex by using <code>/nds</code> or by adding <code>natdex</code> as a parameter.<br/>` +
			`Searching for a Pok\u00e9mon with both egg group and type parameters can be differentiated by adding the suffix <code>group</code> onto the egg group parameter; e.g., seaching for <code>grass, grass group</code> will show all Grass types in the Grass egg group.<br/>` +
			`The parameter <code>monotype</code> will only show Pok\u00e9mon that are single-typed.<br/>` +
			`The order of the parameters does not matter.<br/>`
		);
	},

	rollmove: 'randommove',
	randmove: 'randommove',
	randommove(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast(true)) return;
		const targets = target.split(",");
		const targetsBuffer = [];
		let qty;
		for (const arg of targets) {
			if (!arg) continue;
			const num = Number(arg);
			if (Number.isInteger(num)) {
				if (qty) return this.errorReply("Only specify the number of Pok\u00e9mon Moves once.");
				qty = num;
				if (qty < 1 || 15 < qty) return this.errorReply("Number of random Pok\u00e9mon Moves must be between 1 and 15.");
				targetsBuffer.push(`random${qty}`);
			} else {
				targetsBuffer.push(arg);
			}
		}
		if (!qty) targetsBuffer.push("random1");

		return runSearch({
			tar: targetsBuffer.join(","),
			cmd: 'randmove',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast(true)) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	randommovehelp: [
		`/randommove - Generates random Pok\u00e9mon Moves based on given search conditions.`,
		`/randommove uses the same parameters as /movesearch (see '/help ms').`,
		`Adding a number as a parameter returns that many random Pok\u00e9mon Moves, e.g., '/randmove 6' returns 6 random Pok\u00e9mon Moves.`,
	],
	rollpokemon: 'randompokemon',
	randpoke: 'randompokemon',
	randompokemon(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast(true)) return;
		const targets = target.split(",");
		const targetsBuffer = [];
		let qty;
		for (const arg of targets) {
			if (!arg) continue;
			const num = Number(arg);
			if (Number.isInteger(num)) {
				if (qty) return this.errorReply("Only specify the number of Pok\u00e9mon once.");
				qty = num;
				if (qty < 1 || 15 < qty) return this.errorReply("Number of random Pok\u00e9mon must be between 1 and 15.");
				targetsBuffer.push(`random${qty}`);
			} else {
				targetsBuffer.push(arg);
			}
		}
		if (!qty) targetsBuffer.push("random1");

		return runSearch({
			tar: targetsBuffer.join(","),
			cmd: 'randpoke',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast(true)) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	randompokemonhelp: [
		`/randompokemon - Generates random Pok\u00e9mon based on given search conditions.`,
		`/randompokemon uses the same parameters as /dexsearch (see '/help ds').`,
		`Adding a number as a parameter returns that many random Pok\u00e9mon, e.g., '/randpoke 6' returns 6 random Pok\u00e9mon.`,
	],

	ms: 'movesearch',
	ms1: 'movesearch',
	ms2: 'movesearch',
	ms3: 'movesearch',
	ms4: 'movesearch',
	ms5: 'movesearch',
	ms6: 'movesearch',
	ms7: 'movesearch',
	ms8: 'movesearch',
	msearch: 'movesearch',
	nms: 'movesearch',
	movesearch(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast()) return;
		if (!target) return this.parse('/help movesearch');
		const targetGen = parseInt(cmd[cmd.length - 1]);
		if (targetGen) target += `, maxgen${targetGen}`;
		if (cmd === 'nms') target += ', natdex';
		return runSearch({
			tar: target,
			cmd: 'movesearch',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	movesearchhelp() {
		this.sendReplyBox(
			`<code>/movesearch [parameter], [parameter], [parameter], ...</code>: searches for moves that fulfill the selected criteria.<br/>` +
			`Search categories are: type, category, gen, contest condition, flag, status inflicted, type boosted, Pok\u00e9mon targeted, and numeric range for base power, pp, priority, and accuracy.<br/>` +
			`Types can be followed by <code> type</code> for clarity; e.g., <code>dragon type</code>.<br/>` +
			`Stat boosts must be preceded with <code>boosts </code>, and stat-lowering moves with <code>lowers </code>; e.g., <code>boosts attack</code> searches for moves that boost the Attack stat of either Pok\u00e9mon.<br/>` +
			`Z-stat boosts must be preceded with <code>zboosts </code>; e.g., <code>zboosts accuracy</code> searches for all Status moves with Z-Effects that boost the user's accuracy.<br/>` +
			`Moves that have a Z-Effect of fully restoring the user's health can be searched for with <code>zrecovery</code>.<br/>` +
			`Move targets must be preceded with <code>targets </code>; e.g., <code>targets user</code> searches for moves that target the user.<br/>` +
			`Valid move targets are: one ally, user or ally, one adjacent opponent, all Pokemon, all adjacent Pokemon, all adjacent opponents, user and allies, user's side, user's team, any Pokemon, opponent's side, one adjacent Pokemon, random adjacent Pokemon, scripted, and user.<br/>` +
			`Inequality ranges use the characters <code>></code> and <code><</code>.<br/>` +
			`Parameters can be excluded through the use of <code>!</code>; e.g., <code>!water type</code> excludes all Water-type moves.<br/>` +
			`<code>asc</code> or <code>desc</code> following a move property will arrange the names in ascending or descending order of that property, respectively; e.g., <code>basepower asc</code> will arrange moves in ascending order of their base powers.<br/>` +
			`Valid flags are: authentic (bypasses substitute), bite, bullet, charge, contact, dance, defrost, gravity, mirror (reflected by mirror move), ohko, powder, priority, protect, pulse, punch, recharge, recovery, reflectable, secondary, snatch, sound, and zmove.<br/>` +
			`A search that includes <code>!protect</code> will show all moves that bypass protection.<br/>` +
			`<code>protection</code> as a parameter will search protection moves like Protect, Detect, etc.<br/>` +
			`<code>max</code> or <code>gmax</code> as parameters will search for Max Moves and G-Max moves respectively.<br/>` +
			`Parameters separated with <code>|</code> will be searched as alternatives for each other; e.g., <code>fire | water</code> searches for all moves that are either Fire type or Water type.<br/>` +
			`If a Pok\u00e9mon is included as a parameter, only moves from its movepool will be included in the search.<br/>` +
			`You can search for info in a specific generation by appending the generation to ms; e.g. <code>ms1 normal</code> searches for all moves that were Normal type in Generation I.<br/>` +
			`<code>/ms</code> will search the Galar Moves; you can search the National Moves by using <code>/nms</code> or by adding <code>natdex</code> as a parameter.<br/>` +
			`The order of the parameters does not matter.`
		);
	},

	isearch: 'itemsearch',
	is: 'itemsearch',
	is2: 'itemsearch',
	is3: 'itemsearch',
	is4: 'itemsearch',
	is5: 'itemsearch',
	is6: 'itemsearch',
	is7: 'itemsearch',
	is8: 'itemsearch',
	itemsearch(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast()) return;
		if (!target) return this.parse('/help itemsearch');
		const targetGen = parseInt(cmd[cmd.length - 1]);
		if (targetGen) target += ` maxgen${targetGen}`;

		return runSearch({
			tar: target,
			cmd: 'itemsearch',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	itemsearchhelp() {
		this.sendReplyBox(
			`<code>/itemsearch [item description]</code>: finds items that match the given keywords.<br/>` +
			`This command accepts natural language. (tip: fewer words tend to work better)<br/>` +
			`The <code>gen</code> keyword can be used to search for items introduced in a given generation; e.g., <code>/is gen4</code> searches for items introduced in Generation 4.<br/>` +
			`To search for items within a generation, append the generation to <code>/is</code> or use the <code>maxgen</code> keyword; e.g., <code>/is4 Water-type</code> or <code>/is maxgen4 Water-type</code> searches for items whose Generation 4 description includes "Water-type".<br/>` +
			`Searches with <code>fling</code> in them will find items with the specified Fling behavior.<br/>` +
			`Searches with <code>natural gift</code> in them will find items with the specified Natural Gift behavior.`
		);
	},

	asearch: 'abilitysearch',
	as: 'abilitysearch',
	as3: 'abilitysearch',
	as4: 'abilitysearch',
	as5: 'abilitysearch',
	as6: 'abilitysearch',
	as7: 'abilitysearch',
	as8: 'abilitysearch',
	abilitysearch(target, room, user, connection, cmd, message) {
		if (!this.canBroadcast()) return;
		if (!target) return this.parse('/help abilitysearch');
		const targetGen = parseInt(cmd[cmd.length - 1]);
		if (targetGen) target += ` maxgen${targetGen}`;

		return runSearch({
			tar: target,
			cmd: 'abilitysearch',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: (this.broadcastMessage ? "" : message),
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			} else if (response.dt) {
				(Chat.commands.data as Chat.ChatHandler).call(
					this, response.dt, room, user, connection, 'dt', this.broadcastMessage ? "" : message
				);
			}
			this.update();
		});
	},
	abilitysearchhelp() {
		this.sendReplyBox(
			`<code>/abilitysearch [ability description]</code>: finds abilities that match the given keywords.<br/>` +
			`This command accepts natural language. (tip: fewer words tend to work better)<br/>` +
			`The <code>gen</code> keyword can be used to search for abilities introduced in a given generation; e.g., <code>/as gen4</code> searches for abilities introduced in Generation 4.<br/>` +
			`To search for abilities within a generation, append the generation to <code>/as</code> or use the <code>maxgen</code> keyword; e.g., <code>/as4 Water-type</code> or <code>/as maxgen4 Water-type</code> searches for abilities whose Generation 4 description includes "Water-type".`
		);
	},

	learnset: 'learn',
	learnall: 'learn',
	learn5: 'learn',
	rbylearn: 'learn',
	gsclearn: 'learn',
	advlearn: 'learn',
	dpplearn: 'learn',
	bw2learn: 'learn',
	oraslearn: 'learn',
	usumlearn: 'learn',
	learn(target, room, user, connection, cmd, message) {
		if (!target) return this.parse('/help learn');
		if (!this.canBroadcast()) return;

		return runSearch({
			tar: target,
			cmd: 'learn',
			canAll: !this.broadcastMessage || !!room?.settings.isPersonal,
			message: cmd,
		}).then(response => {
			if (!response.error && !this.runBroadcast()) return;
			if (response.error) {
				this.errorReply(response.error);
			} else if (response.reply) {
				this.sendReplyBox(response.reply);
			}
			this.update();
		});
	},
	learnhelp: [
		`/learn [ruleset], [pokemon], [move, move, ...] - Displays how the Pok\u00e9mon can learn the given moves, if it can at all.`,
		`!learn [ruleset], [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ # &`,
		`Specifying a ruleset is entirely optional. The ruleset can be a format, a generation (e.g.: gen3) or 'pentagon'. A value of 'pentagon' indicates that trading from previous generations is not allowed.`,
		`/learn5 displays how the Pok\u00e9mon can learn the given moves at level 5, if it can at all.`,
		`/learnall displays all of the possible fathers for egg moves.`,
		`/learn can also be prefixed by a generation acronym (e.g.: /dpplearn) to indicate which generation is used. Valid options are: rby gsc adv dpp bw2 oras usum`,
	],
};

function runDexsearch(target: string, cmd: string, canAll: boolean, message: string) {
	const searches: DexOrGroup[] = [];
	const allTiers: {[k: string]: TierTypes.Singles | TierTypes.Other} = Object.assign(Object.create(null), {
		uber: 'Uber', ubers: 'Uber', ou: 'OU',
		uubl: 'UUBL', uu: 'UU',
		rubl: 'RUBL', ru: 'RU',
		nubl: 'NUBL', nu: 'NU', untiered: '(NU)',
		publ: 'PUBL', pu: 'PU', zu: '(PU)',
		nfe: 'NFE',
		lcuber: 'LC Uber', lcubers: 'LC Uber', lc: 'LC',
		cap: 'CAP', caplc: 'CAP LC', capnfe: 'CAP NFE',
	});
	const allDoublesTiers: {[k: string]: TierTypes.Singles | TierTypes.Other} = Object.assign(Object.create(null), {
		doublesubers: 'DUber', doublesuber: 'DUber', duber: 'DUber', dubers: 'DUber',
		doublesou: 'DOU', dou: 'DOU',
		doublesbl: 'DBL', dbl: 'DBL',
		doublesuu: 'DUU', duu: 'DUU',
		doublesnu: '(DUU)', dnu: '(DUU)',
	});
	const allTypes = Object.create(null);
	for (const i in Dex.data.TypeChart) {
		allTypes[toID(i)] = i;
	}
	const allColors = ['green', 'red', 'blue', 'white', 'brown', 'yellow', 'purple', 'pink', 'gray', 'black'];
	const allEggGroups: {[k: string]: string} = Object.assign(Object.create(null), {
		amorphous: 'Amorphous',
		bug: 'Bug',
		ditto: 'Ditto',
		dragon: 'Dragon',
		fairy: 'Fairy',
		field: 'Field',
		flying: 'Flying',
		grass: 'Grass',
		humanlike: 'Human-Like',
		mineral: 'Mineral',
		monster: 'Monster',
		undiscovered: 'Undiscovered',
		water1: 'Water 1',
		water2: 'Water 2',
		water3: 'Water 3',
	});
	const allFormes = ['alola', 'galar', 'primal', 'therian', 'totem'];
	const allStats = ['hp', 'atk', 'def', 'spa', 'spd', 'spe', 'bst', 'weight', 'height', 'gen'];
	const allStatAliases: {[k: string]: string} = {
		attack: 'atk', defense: 'def', specialattack: 'spa', spc: 'spa', special: 'spa', spatk: 'spa',
		specialdefense: 'spd', spdef: 'spd', speed: 'spe', wt: 'weight', ht: 'height', generation: 'gen',
	};
	let showAll = false;
	let sort = null;
	let megaSearch = null;
	let gmaxSearch = null;
	let tierSearch = null;
	let capSearch = null;
	let nationalSearch = null;
	let fullyEvolvedSearch = null;
	let singleTypeSearch = null;
	let randomOutput = 0;
	let maxGen = 0;
	const validParameter = (cat: string, param: string, isNotSearch: boolean, input: string) => {
		const uniqueTraits = ['colors', 'gens'];
		for (const group of searches) {
			const g = group[cat as keyof DexOrGroup];
			if (g === undefined) continue;
			if (typeof g !== 'boolean' && g[param] === undefined) {
				if (uniqueTraits.includes(cat)) {
					for (const currentParam in g) {
						if (g[currentParam] !== isNotSearch && !isNotSearch) return `A Pok&eacute;mon cannot have multiple ${cat}.`;
					}
				}
				continue;
			}
			if (typeof g !== 'boolean' && g[param] === isNotSearch) {
				return `A search cannot both include and exclude '${input}'.`;
			} else {
				return `The search included '${(isNotSearch ? "!" : "") + input}' more than once.`;
			}
		}
		return false;
	};

	for (const andGroup of target.split(',')) {
		const orGroup: DexOrGroup = {
			abilities: {}, tiers: {}, doublesTiers: {}, colors: {}, 'egg groups': {}, formes: {},
			gens: {}, moves: {}, types: {}, resists: {}, weak: {}, stats: {}, skip: false,
		};
		const parameters = andGroup.split("|");
		if (parameters.length > 3) return {error: "No more than 3 alternatives for each parameter may be used."};
		for (const parameter of parameters) {
			let isNotSearch = false;
			target = parameter.trim().toLowerCase();
			if (target.charAt(0) === '!') {
				isNotSearch = true;
				target = target.substr(1);
			}

			const targetAbility = Dex.getAbility(target);
			if (targetAbility.exists) {
				const invalid = validParameter("abilities", targetAbility.id, isNotSearch, targetAbility.name);
				if (invalid) return {error: invalid};
				orGroup.abilities[targetAbility.name] = !isNotSearch;
				continue;
			}

			if (toID(target) in allTiers) {
				target = allTiers[toID(target)];
				if (target.startsWith("CAP")) {
					if (capSearch === isNotSearch) return {error: "A search cannot both include and exclude CAP tiers."};
					capSearch = !isNotSearch;
				}
				const invalid = validParameter("tiers", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				tierSearch = tierSearch || !isNotSearch;
				orGroup.tiers[target] = !isNotSearch;
				continue;
			}

			if (toID(target) in allDoublesTiers) {
				target = allDoublesTiers[toID(target)];
				const invalid = validParameter("doubles tiers", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				tierSearch = tierSearch || !isNotSearch;
				orGroup.doublesTiers[target] = !isNotSearch;
				continue;
			}

			if (allColors.includes(target)) {
				target = target.charAt(0).toUpperCase() + target.slice(1);
				const invalid = validParameter("colors", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				orGroup.colors[target] = !isNotSearch;
				continue;
			}

			const targetMove = Dex.getMove(target);
			if (targetMove.exists) {
				const invalid = validParameter("moves", targetMove.id, isNotSearch, target);
				if (invalid) return {error: invalid};
				orGroup.moves[targetMove.id] = !isNotSearch;
				continue;
			}

			let targetType;
			if (target.endsWith('type')) {
				targetType = toID(target.substring(0, target.indexOf('type')));
			} else {
				targetType = toID(target);
			}
			if (targetType in allTypes) {
				target = allTypes[targetType];
				const invalid = validParameter("types", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				if ((orGroup.types[target] && isNotSearch) || (orGroup.types[target] === false && !isNotSearch)) {
					return {error: 'A search cannot both exclude and include a type.'};
				}
				orGroup.types[target] = !isNotSearch;
				continue;
			}

			if (['mono', 'monotype'].includes(toID(target))) {
				singleTypeSearch = !isNotSearch;
				orGroup.skip = true;
				continue;
			}

			if (target.substr(0, 6) === 'maxgen') {
				maxGen = parseInt(target[6]);
				if (!maxGen || maxGen < 1 || maxGen > 8) return {error: "The generation must be between 1 and 8"};
				orGroup.skip = true;
				continue;
			}

			if (target === 'natdex') {
				nationalSearch = true;
				orGroup.skip = true;
				continue;
			}

			let groupIndex = target.indexOf('group');
			if (groupIndex === -1) groupIndex = target.length;
			if (groupIndex !== target.length || toID(target) in allEggGroups) {
				target = toID(target.substring(0, groupIndex));
				if (target in allEggGroups) {
					target = allEggGroups[toID(target)];
					const invalid = validParameter("egg groups", target, isNotSearch, target);
					if (invalid) return {error: invalid};
					orGroup['egg groups'][target] = !isNotSearch;
					continue;
				} else {
					return {error: `'${target}' is not a recognized egg group.`};
				}
			}
			if (toID(target) in allEggGroups) {
				target = allEggGroups[toID(target)];
				const invalid = validParameter("egg groups", target, isNotSearch, target);
				if (invalid) return {error: invalid};
				orGroup['egg groups'][target] = !isNotSearch;
				continue;
			}

			let targetInt = 0;
			if (target.substr(0, 1) === 'g' && Number.isInteger(parseFloat(target.substr(1)))) {
				targetInt = parseInt(target.substr(1).trim());
			} else if (target.substr(0, 3) === 'gen' && Number.isInteger(parseFloat(target.substr(3)))) {
				targetInt = parseInt(target.substr(3).trim());
			}
			if (0 < targetInt && targetInt < 9) {
				const invalid = validParameter("gens", String(targetInt), isNotSearch, target);
				if (invalid) return {error: invalid};
				orGroup.gens[targetInt] = !isNotSearch;
				continue;
			}

			if (target.endsWith(' asc') || target.endsWith(' desc')) {
				if (parameters.length > 1) return {error: `The parameter '${target.split(' ')[1]}' cannot have alternative parameters`};
				const stat = allStatAliases[toID(target.split(' ')[0])] || toID(target.split(' ')[0]);
				if (!allStats.includes(stat)) return {error: `'${escapeHTML(target)}' did not contain a valid stat.`};
				sort = `${stat}${target.endsWith(' asc') ? '+' : '-'}`;
				orGroup.skip = true;
				break;
			}

			if (target === 'all') {
				if (!canAll) return {error: "A search with the parameter 'all' cannot be broadcast."};
				if (parameters.length > 1) return {error: "The parameter 'all' cannot have alternative parameters"};
				showAll = true;
				orGroup.skip = true;
				break;
			}

			if (target.substr(0, 6) === 'random' && cmd === 'randpoke') {
				// Validation for this is in the /randpoke command
				randomOutput = parseInt(target.substr(6));
				orGroup.skip = true;
				continue;
			}

			if (allFormes.includes(toID(target))) {
				target = toID(target);
				orGroup.formes[target] = !isNotSearch;
				continue;
			}

			if (target === 'megas' || target === 'mega') {
				if (megaSearch === isNotSearch) return {error: "A search cannot include and exclude 'mega'."};
				if (parameters.length > 1) return {error: "The parameter 'mega' cannot have alternative parameters"};
				megaSearch = !isNotSearch;
				orGroup.skip = true;
				break;
			}

			if (target === 'gmax' || target === 'gigantamax') {
				if (gmaxSearch === isNotSearch) return {error: "A search cannot include and exclude 'gigantamax'."};
				if (parameters.length > 1) return {error: "The parameter 'gigantamax' cannot have alternative parameters"};
				gmaxSearch = !isNotSearch;
				orGroup.skip = true;
				break;
			}

			if (['fully evolved', 'fullyevolved', 'fe'].includes(target)) {
				if (fullyEvolvedSearch === isNotSearch) return {error: "A search cannot include and exclude 'fully evolved'."};
				if (parameters.length > 1) return {error: "The parameter 'fully evolved' cannot have alternative parameters"};
				fullyEvolvedSearch = !isNotSearch;
				orGroup.skip = true;
				break;
			}

			if (target === 'recovery') {
				if (parameters.length > 1) return {error: "The parameter 'recovery' cannot have alternative parameters"};
				const recoveryMoves = [
					"recover", "roost", "moonlight", "morningsun", "synthesis", "milkdrink",
					"slackoff", "softboiled", "wish", "healorder", "shoreup", "lifedew",
				];
				for (const move of recoveryMoves) {
					const invalid = validParameter("moves", move, isNotSearch, target);
					if (invalid) return {error: invalid};
					if (isNotSearch) {
						const bufferObj: {moves: {[k: string]: boolean}} = {moves: {}};
						bufferObj.moves[move] = false;
						searches.push(bufferObj as DexOrGroup);
					} else {
						orGroup.moves[move] = true;
					}
				}
				if (isNotSearch) orGroup.skip = true;
				break;
			}

			if (target === 'zrecovery') {
				if (parameters.length > 1) return {error: "The parameter 'zrecovery' cannot have alternative parameters"};
				const recoveryMoves = [
					"aromatherapy", "bellydrum", "conversion2", "haze", "healbell", "mist",
					"psychup", "refresh", "spite", "stockpile", "teleport", "transform",
				];
				for (const moveid of recoveryMoves) {
					const invalid = validParameter("moves", moveid, isNotSearch, target);
					if (invalid) return {error: invalid};
					if (isNotSearch) {
						const bufferObj: {moves: {[k: string]: boolean}} = {moves: {}};
						bufferObj.moves[moveid] = false;
						searches.push(bufferObj as DexOrGroup);
					} else {
						orGroup.moves[moveid] = true;
					}
				}
				if (isNotSearch) orGroup.skip = true;
				break;
			}

			if (target === 'priority') {
				if (parameters.length > 1) return {error: "The parameter 'priority' cannot have alternative parameters"};
				for (const move in Dex.data.Moves) {
					const moveData = Dex.getMove(move);
					if (moveData.category === "Status" || moveData.id === "bide") continue;
					if (moveData.priority > 0) {
						const invalid = validParameter("moves", move, isNotSearch, target);
						if (invalid) return {error: invalid};
						if (isNotSearch) {
							const bufferObj: {moves: {[k: string]: boolean}} = {moves: {}};
							bufferObj.moves[move] = false;
							searches.push(bufferObj as DexOrGroup);
						} else {
							orGroup.moves[move] = true;
						}
					}
				}
				if (isNotSearch) orGroup.skip = true;
				break;
			}

			if (target.substr(0, 8) === 'resists ') {
				const targetResist = target.substr(8, 1).toUpperCase() + target.substr(9);
				if (targetResist in Dex.data.TypeChart) {
					const invalid = validParameter("resists", targetResist, isNotSearch, target);
					if (invalid) return {error: invalid};
					orGroup.resists[targetResist] = !isNotSearch;
					continue;
				} else {
					return {error: `'${targetResist}' is not a recognized type.`};
				}
			}

			if (target.substr(0, 5) === 'weak ') {
				const targetWeak = target.substr(5, 1).toUpperCase() + target.substr(6);
				if (targetWeak in Dex.data.TypeChart) {
					const invalid = validParameter("weak", targetWeak, isNotSearch, target);
					if (invalid) return {error: invalid};
					orGroup.weak[targetWeak] = !isNotSearch;
					continue;
				} else {
					return {error: `'${targetWeak}' is not a recognized type.`};
				}
			}

			const inequality = target.search(/>|<|=/);
			let inequalityString;
			if (inequality >= 0) {
				if (isNotSearch) return {error: "You cannot use the negation symbol '!' in stat ranges."};
				if (target.charAt(inequality + 1) === '=') {
					inequalityString = target.substr(inequality, 2);
				} else {
					inequalityString = target.charAt(inequality);
				}
				const targetParts = target.replace(/\s/g, '').split(inequalityString);
				let num;
				let stat;
				const directions: Direction[] = [];
				if (!isNaN(parseFloat(targetParts[0]))) {
					// e.g. 100 < spe
					num = parseFloat(targetParts[0]);
					stat = targetParts[1];
					if (inequalityString[0] === '>') directions.push('less');
					if (inequalityString[0] === '<') directions.push('greater');
				} else if (!isNaN(parseFloat(targetParts[1]))) {
					// e.g. spe > 100
					num = parseFloat(targetParts[1]);
					stat = targetParts[0];
					if (inequalityString[0] === '<') directions.push('less');
					if (inequalityString[0] === '>') directions.push('greater');
				} else {
					return {error: `No value given to compare with '${escapeHTML(target)}'.`};
				}
				if (inequalityString.slice(-1) === '=') directions.push('equal');
				if (stat in allStatAliases) stat = allStatAliases[stat];
				if (!allStats.includes(stat)) return {error: `'${escapeHTML(target)}' did not contain a valid stat.`};
				if (!orGroup.stats[stat]) orGroup.stats[stat] = Object.create(null);
				for (const direction of directions) {
					if (orGroup.stats[stat][direction]) return {error: `Invalid stat range for ${stat}.`};
					orGroup.stats[stat][direction] = num;
				}
				continue;
			}
			return {error: `'${escapeHTML(target)}' could not be found in any of the search categories.`};
		}
		if (!orGroup.skip) {
			searches.push(orGroup);
		}
	}
	if (
		showAll && searches.length === 0 && !maxGen && singleTypeSearch === null &&
		megaSearch === null && gmaxSearch === null && fullyEvolvedSearch === null && sort === null
	) {
		return {
			error: "No search parameters other than 'all' were found. Try '/help dexsearch' for more information on this command.",
		};
	}

	if (!maxGen) maxGen = 8;
	const mod = Dex.mod('gen' + maxGen);
	const dex: {[k: string]: Species} = {};
	for (const pokemon in mod.data.Pokedex) {
		const species = mod.getSpecies(pokemon);
		const megaSearchResult = (
			megaSearch === null || (megaSearch === true && species.isMega) ||
			(megaSearch === false && !species.isMega)
		);
		const gmaxSearchResult = (
			gmaxSearch === null || (gmaxSearch === true && species.name.endsWith('-Gmax')) ||
			(gmaxSearch === false && !species.name.endsWith('-Gmax'))
		);
		const fullyEvolvedSearchResult = (
			fullyEvolvedSearch === null ||
			(fullyEvolvedSearch === true && !species.nfe) ||
			(fullyEvolvedSearch === false && species.nfe)
		);
		if (
			species.gen <= maxGen &&
			(
				(
					nationalSearch &&
					species.isNonstandard &&
					!["Custom", "Glitch", "Pokestar"].includes(species.isNonstandard)
				) ||
				(species.tier !== 'Unreleased' && species.tier !== 'Illegal')
			) &&
			(!species.tier.startsWith("CAP") || capSearch) &&
			megaSearchResult &&
			gmaxSearchResult &&
			fullyEvolvedSearchResult
		) {
			dex[pokemon] = species;
		}
	}

	// Prioritize searches with the least alternatives.
	const accumulateKeyCount = (count: number, searchData: AnyObject) =>
		count + (typeof searchData === 'object' ? Object.keys(searchData).length : 0);
	searches.sort(
		(a, b) => Object.values(a).reduce(accumulateKeyCount, 0) - Object.values(b).reduce(accumulateKeyCount, 0)
	);

	for (const alts of searches) {
		if (alts.skip) continue;
		for (const mon in dex) {
			let matched = false;
			if (alts.gens && Object.keys(alts.gens).length) {
				if (alts.gens[dex[mon].gen]) continue;
				if (Object.values(alts.gens).includes(false) && alts.gens[dex[mon].gen] !== false) continue;
			}

			if (alts.colors && Object.keys(alts.colors).length) {
				if (alts.colors[dex[mon].color]) continue;
				if (Object.values(alts.colors).includes(false) && alts.colors[dex[mon].color] !== false) continue;
			}

			for (const eggGroup in alts['egg groups']) {
				if (dex[mon].eggGroups.includes(eggGroup) === alts['egg groups'][eggGroup]) {
					matched = true;
					break;
				}
			}

			if (alts.tiers && Object.keys(alts.tiers).length) {
				let tier = dex[mon].tier;
				if (tier[0] === '(' && tier !== '(PU)' && tier !== '(NU)') tier = tier.slice(1, -1) as TierTypes.Singles;
				// if (tier === 'New') tier = 'OU';
				if (alts.tiers[tier]) continue;
				if (Object.values(alts.tiers).includes(false) && alts.tiers[tier] !== false) continue;
				// LC handling, checks for LC Pokemon in higher tiers that need to be handled separately,
				// as well as event-only Pokemon that are not eligible for LC despite being the first stage
				let format = Dex.getFormat('gen' + maxGen + 'lc');
				if (!format.exists) format = Dex.getFormat('gen8lc');
				if (
					alts.tiers.LC &&
					!dex[mon].prevo &&
					dex[mon].evos.some(evo => mod.getSpecies(evo).gen <= mod.gen) &&
					!format.banlist.includes(dex[mon].name) &&
					!format.banlist.includes(dex[mon].name + "-Base")
				) {
					const lsetData = Dex.getLearnsetData(dex[mon].id);
					if (lsetData.exists && lsetData.eventData && lsetData.eventOnly) {
						let validEvents = 0;
						for (const event of lsetData.eventData) {
							if (event.level && event.level <= 5) validEvents++;
						}
						if (validEvents > 0) continue;
					} else {
						continue;
					}
				}
			}

			if (alts.doublesTiers && Object.keys(alts.doublesTiers).length) {
				let tier = dex[mon].doublesTier;
				if (tier && tier[0] === '(' && tier !== '(DUU)') tier = tier.slice(1, -1) as TierTypes.Doubles;
				if (alts.doublesTiers[tier]) continue;
				if (Object.values(alts.doublesTiers).includes(false) && alts.doublesTiers[tier] !== false) continue;
			}

			for (const type in alts.types) {
				if (dex[mon].types.includes(type) === alts.types[type]) {
					matched = true;
					break;
				}
			}
			if (matched) continue;

			for (const type in alts.resists) {
				let effectiveness = 0;
				const notImmune = mod.getImmunity(type, dex[mon]);
				if (notImmune) effectiveness = mod.getEffectiveness(type, dex[mon]);
				if (!alts.resists[type]) {
					if (notImmune && effectiveness >= 0) matched = true;
				} else {
					if (!notImmune || effectiveness < 0) matched = true;
				}
			}
			if (matched) continue;

			for (const type in alts.weak) {
				let effectiveness = 0;
				const notImmune = mod.getImmunity(type, dex[mon]);
				if (notImmune) effectiveness = mod.getEffectiveness(type, dex[mon]);
				if (alts.weak[type]) {
					if (notImmune && effectiveness >= 1) matched = true;
				} else {
					if (!notImmune || effectiveness < 1) matched = true;
				}
			}
			if (matched) continue;

			for (const ability in alts.abilities) {
				if (Object.values(dex[mon].abilities).includes(ability) === alts.abilities[ability]) {
					matched = true;
					break;
				}
			}
			if (matched) continue;

			for (const forme in alts.formes) {
				if (toID(dex[mon].forme).includes(forme) === alts.formes[forme]) {
					matched = true;
					break;
				}
			}
			if (matched) continue;

			for (const stat in alts.stats) {
				let monStat = 0;
				if (stat === 'bst') {
					monStat = dex[mon].bst;
				} else if (stat === 'weight') {
					monStat = dex[mon].weighthg / 10;
				} else if (stat === 'height') {
					monStat = dex[mon].heightm;
				} else if (stat === 'gen') {
					monStat = dex[mon].gen;
				} else {
					monStat = dex[mon].baseStats[stat as StatName];
				}
				if (typeof alts.stats[stat].less === 'number') {
					if (monStat < alts.stats[stat].less) {
						matched = true;
						break;
					}
				}
				if (typeof alts.stats[stat].greater === 'number') {
					if (monStat > alts.stats[stat].greater) {
						matched = true;
						break;
					}
				}
				if (typeof alts.stats[stat].equal === 'number') {
					if (monStat === alts.stats[stat].equal) {
						matched = true;
						break;
					}
				}
			}
			if (matched) continue;

			const validator = TeamValidator.get(nationalSearch ? `gen8nationaldexag` : `gen${maxGen}ou`);
			const pokemonSource = validator.allSources();
			for (const move of Object.keys(alts.moves).map(x => Dex.getMove(x))) {
				if (move.gen <= maxGen && !validator.checkLearnset(move, dex[mon], pokemonSource) === alts.moves[move.id]) {
					matched = true;
					break;
				}
				if (!pokemonSource.size()) break;
			}
			if (matched) continue;

			delete dex[mon];
		}
	}
	let results: string[] = [];
	for (const mon of Object.keys(dex).sort()) {
		if (singleTypeSearch !== null && (dex[mon].types.length === 1) !== singleTypeSearch) continue;
		const isAlola = dex[mon].forme === "Alola" && dex[mon].name !== "Pikachu-Alola";
		const allowGmax = (gmaxSearch || tierSearch);
		if (!isAlola && dex[mon].baseSpecies && results.includes(dex[mon].baseSpecies)) continue;
		if (dex[mon].name.endsWith('-Gmax') && !allowGmax) continue;
{'fraction_non_alphanumeric': 0.1630966658671144, 'fraction_numerical': 0.0064044135284240826, 'mean_word_length': 3.6922341024198087, 'pattern_counts': {'":': 0, '<': 463, '<?xml version=': 0, '>': 489, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5608659', 'n_tokens_mistral': 32383, 'n_tokens_neox': 27460, 'n_words': 7833}