/**
 * new-with-context extension
 *
 * Provides a /new-with-context command that starts a fresh session but carries
 * only the last message from the current conversation into the new session.
 *
 * Usage:
 *   /new-with-context
 *
 * What it does:
 *   1. Finds the last user or assistant message in the current branch
 *   2. Starts a new session
 *   3. Injects that last message as the opening context
 */

import type { ExtensionAPI, SessionEntry } from "@mariozechner/pi-coding-agent";

export default function (pi: ExtensionAPI) {
	pi.registerCommand("new-with-context", {
		description: "Start a new session keeping only the last message as context",
		handler: async (args, ctx) => {
			await ctx.waitForIdle();

			// Collect all message entries from the current branch
			const branch = ctx.sessionManager.getBranch();
			const messageEntries = branch.filter(
				(entry): entry is SessionEntry & { type: "message" } => entry.type === "message",
			);

			if (messageEntries.length === 0) {
				ctx.ui.notify("No messages in current session to carry over.", "info");
				await ctx.newSession();
				return;
			}

			// Grab the last message entry
			const lastEntry = messageEntries[messageEntries.length - 1];
			const lastMessage = lastEntry.message;

			const currentSessionFile = ctx.sessionManager.getSessionFile();

			// Create a new session and inject the last message as opening context
			const result = await ctx.newSession({
				parentSession: currentSessionFile ?? undefined,
				setup: async (sm) => {
					sm.appendMessage(lastMessage);
				},
			});

			if (result.cancelled) {
				ctx.ui.notify("New session cancelled.", "info");
				return;
			}

			// Give a brief summary of what was carried over
			const role = lastMessage.role;
			let preview = "";
			if (role === "user" || role === "assistant") {
				const content = lastMessage.content;
				if (typeof content === "string") {
					preview = content.slice(0, 80);
				} else if (Array.isArray(content)) {
					const textBlock = content.find((c: any) => c.type === "text");
					if (textBlock && "text" in textBlock) {
						preview = (textBlock as { type: "text"; text: string }).text.slice(0, 80);
					}
				}
			} else if (role === "toolResult") {
				preview = `[tool result: ${(lastMessage as any).toolName}]`;
			} else {
				preview = `[${role} message]`;
			}

			if (preview.length === 80) preview += "…";

			ctx.ui.notify(
				`New session started. Carried over last message (${role}): "${preview}"`,
				"success",
			);
		},
	});
}
