import { importExtensionModule } from "@singularity-forge/pi-coding-agent";
import {
	DIRECT_SF_COMMANDS,
	getSfTopLevelCommandCompletions,
	SF_COMMAND_DESCRIPTION,
} from "./catalog.js";

async function dispatchDirectSFCommand(command, args, ctx, pi) {
	const { handleSFCommand } = await importExtensionModule(
		import.meta.url,
		"./dispatcher.js",
	);
	const { setStderrLoggingEnabled } = await importExtensionModule(
		import.meta.url,
		"../workflow-logger.js",
	);
	const previousStderrSetting = setStderrLoggingEnabled(false);
	try {
		const suffix =
			typeof args === "string" && args.trim().length > 0
				? ` ${args.trim()}`
				: "";
		await handleSFCommand(`${command}${suffix}`, ctx, pi);
	} finally {
		setStderrLoggingEnabled(previousStderrSetting);
	}
}

export function registerSFCommands(pi) {
	for (const command of DIRECT_SF_COMMANDS) {
		pi.registerCommand(command.cmd, {
			description: command.desc || SF_COMMAND_DESCRIPTION,
			getArgumentCompletions: (prefix) =>
				getSfTopLevelCommandCompletions(command.cmd, prefix),
			handler: async (args, ctx) => {
				await dispatchDirectSFCommand(command.cmd, args, ctx, pi);
			},
		});
	}
}

export function registerSFCommand(pi) {
	registerSFCommands(pi);
}
