/**
 * Stop — Immediately interrupt the active chat session
 *
 * Registers a /stop slash command that aborts the current agent turn.
 * Also supports /stop with a reason message for logging clarity.
 *
 * Usage: pi -e extensions/stop.ts
 *
 * Commands:
 *   /stop           — abort the current agent turn immediately
 *   /stop <reason>  — abort with a logged reason
 */

import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
import { applyExtensionDefaults } from "./themeMap.ts";

export default function (pi: ExtensionAPI) {
	let activeCtx: ExtensionContext | undefined;

	pi.on("session_start", async (_event, ctx) => {
		applyExtensionDefaults(import.meta.url, ctx);
		activeCtx = ctx;
	});

	pi.on("session_switch", async (_event, ctx) => {
		activeCtx = ctx;
	});

	pi.registerCommand("stop", {
		description: "Immediately interrupt the active agent turn. Usage: /stop [reason]",
		handler: async (args, ctx) => {
			activeCtx = ctx;
			const reason = (args || "").trim();
			ctx.abort();
			const msg = reason
				? `🛑 Session aborted: ${reason}`
				: "🛑 Session aborted.";
			ctx.ui.notify(msg, "warning");
		},
	});
}
