import type { SlashCommand } from "../types/commands";

/** Keep in sync with backend/slash/dispatch.ts WEBUI_BUILTIN_SLASH_NAMES */
const WEBUI_BUILTIN_SLASH_NAMES = new Set([
	"compact",
	"new",
	"reload",
	"clone",
	"name",
	"model",
	"session",
	"export",
	"copy",
]);

export function isWebUiSlashCommand(command: SlashCommand): boolean {
	if (command.source === "extension" || command.source === "prompt" || command.source === "skill") {
		return true;
	}
	return WEBUI_BUILTIN_SLASH_NAMES.has(command.name);
}

export function filterWebUiSlashCommands(commands: SlashCommand[]): SlashCommand[] {
	return commands.filter(isWebUiSlashCommand);
}

export function parseSlashCommandInput(text: string): { query: string } | null {
	const trimmed = text.trimStart();
	if (!trimmed.startsWith("/")) return null;
	if (trimmed.includes(" ")) return null;
	return { query: trimmed.slice(1) };
}

export function filterSlashCommands(commands: SlashCommand[], query: string): SlashCommand[] {
	const normalized = query.trim().toLowerCase();
	if (!normalized) return commands;

	return commands
		.filter((command) => command.name.toLowerCase().includes(normalized))
		.sort((a, b) => {
			const aStarts = a.name.toLowerCase().startsWith(normalized);
			const bStarts = b.name.toLowerCase().startsWith(normalized);
			if (aStarts !== bStarts) return aStarts ? -1 : 1;
			return a.name.localeCompare(b.name);
		});
}

export function applySlashCompletion(current: string, commandName: string): string {
	const leadingSpaces = current.match(/^\s*/)?.[0] ?? "";
	return `${leadingSpaces}/${commandName} `;
}

export function slashCommandSourceLabel(source: SlashCommand["source"]): string {
	switch (source) {
		case "builtin":
			return "内置";
		case "extension":
			return "扩展";
		case "prompt":
			return "指令";
		case "skill":
			return "技能";
	}
}
