/**
 * /search-provider slash command.
 *
 * Lets users switch between tavily, minimax, brave, serper, exa, ollama, combosearch, and auto search backends.
 * Supports direct arg (`/search-provider tavily`) or interactive select UI.
 * Tab completion provides the valid options with key status.
 *
 * All provider logic lives in provider.ts (S01) — this is pure UI wiring.
 */
import {
	getBraveApiKey,
	getExaApiKey,
	getMiniMaxSearchApiKey,
	getOllamaApiKey,
	getSearchProviderPreference,
	getSerperApiKey,
	getTavilyApiKey,
	resolveSearchProvider,
	setSearchProviderPreference,
} from "./provider.js";

const VALID_PREFERENCES = [
	"tavily",
	"minimax",
	"brave",
	"serper",
	"exa",
	"ollama",
	"combosearch",
	"auto",
];
function keyStatus(provider) {
	if (provider === "tavily") return getTavilyApiKey() ? "✓" : "✗";
	if (provider === "minimax") return getMiniMaxSearchApiKey() ? "✓" : "✗";
	if (provider === "serper") return getSerperApiKey() ? "✓" : "✗";
	if (provider === "exa") return getExaApiKey() ? "✓" : "✗";
	if (provider === "ollama") return getOllamaApiKey() ? "✓" : "✗";
	return getBraveApiKey() ? "✓" : "✗";
}
function comboStatus() {
	const available = [
		getTavilyApiKey() ? "tavily" : null,
		getMiniMaxSearchApiKey() ? "minimax" : null,
		getBraveApiKey() ? "brave" : null,
		getSerperApiKey() ? "serper" : null,
		getExaApiKey() ? "exa" : null,
		getOllamaApiKey() ? "ollama" : null,
	].filter(Boolean);
	return available.length > 0
		? `${available.length} source${available.length === 1 ? "" : "s"}`
		: "✗";
}
function buildSelectOptions() {
	return [
		`tavily (key: ${keyStatus("tavily")})`,
		`minimax (key: ${keyStatus("minimax")})`,
		`brave (key: ${keyStatus("brave")})`,
		`serper (key: ${keyStatus("serper")})`,
		`exa (key: ${keyStatus("exa")})`,
		`ollama (key: ${keyStatus("ollama")})`,
		`combosearch (${comboStatus()})`,
		`auto`,
	];
}
function parseSelectChoice(choice) {
	if (choice.startsWith("tavily")) return "tavily";
	if (choice.startsWith("minimax")) return "minimax";
	if (choice.startsWith("brave")) return "brave";
	if (choice.startsWith("serper")) return "serper";
	if (choice.startsWith("exa")) return "exa";
	if (choice.startsWith("ollama")) return "ollama";
	if (choice.startsWith("combosearch")) return "combosearch";
	return "auto";
}
export function registerSearchProviderCommand(pi) {
	pi.registerCommand("search-provider", {
		description:
			"Switch search provider (tavily, minimax, brave, serper, exa, ollama, combosearch, auto)",
		getArgumentCompletions(prefix) {
			const trimmed = prefix.trim().toLowerCase();
			return VALID_PREFERENCES.filter((p) => p.startsWith(trimmed)).map((p) => {
				let description;
				if (p === "auto") {
					description = `Auto-select (tavily: ${keyStatus("tavily")}, minimax: ${keyStatus("minimax")}, brave: ${keyStatus("brave")}, serper: ${keyStatus("serper")}, exa: ${keyStatus("exa")}, ollama: ${keyStatus("ollama")})`;
				} else if (p === "combosearch") {
					description = `fan-out aggregator (${comboStatus()})`;
				} else {
					description = `key: ${keyStatus(p)}`;
				}
				return { value: p, label: p, description };
			});
		},
		async handler(args, ctx) {
			const trimmed = args.trim().toLowerCase();
			let chosen;
			if (trimmed && VALID_PREFERENCES.includes(trimmed)) {
				// Direct arg — apply immediately, no select UI
				chosen = trimmed;
			} else {
				// No arg or invalid arg — show interactive select
				const current = getSearchProviderPreference();
				const options = buildSelectOptions();
				const result = await ctx.ui.select(
					`Search provider (current: ${current})`,
					options,
				);
				if (result === undefined) {
					// User cancelled — bail silently
					return;
				}
				chosen = parseSelectChoice(Array.isArray(result) ? result[0] : result);
			}
			setSearchProviderPreference(chosen);
			const effective = resolveSearchProvider();
			const isAnthropic = ctx.model?.provider === "anthropic";
			const nativeNote = isAnthropic
				? "\nNote: Native Anthropic web search is also active (automatic, no API key needed)."
				: "";
			ctx.ui.notify(
				`Search provider set to ${chosen}. Effective provider: ${effective ?? "none (no API keys)"}${nativeNote}`,
				"info",
			);
		},
	});
}
