import { getModel } from "../core/model-registry.js";
import { PROMPT_COMMANDS, getPromptCommand } from "../core/prompt-commands.js";
import { log } from "../core/logger.js";
import { buildUserContentWithAttachments, routePromptCommandInput } from "./prompt-routing.js";
import { toErrorItem } from "./error-item.js";
const GOAL_PLANNER_OUTPUT_MAX_CHARS = 2400;
function messageTextContent(message) {
    if (typeof message.content === "string")
        return message.content;
    return message.content
        .filter((part) => part.type === "text")
        .map((part) => part.text)
        .join("\n");
}
export function collectAssistantTextSince(messages, startIndex, maxChars = GOAL_PLANNER_OUTPUT_MAX_CHARS) {
    const text = messages
        .slice(startIndex)
        .filter((message) => message.role === "assistant")
        .map(messageTextContent)
        .join("\n")
        .trim();
    if (text.length <= maxChars)
        return text;
    return `${text.slice(0, maxChars).trimEnd()}\n[planner output truncated]`;
}
export function buildGoalSetupPromptFromPlanner({ originalGoalPrompt, plannerOutput, }) {
    const compactPlannerOutput = plannerOutput.trim() || "GOAL_PLAN\nresearch=none\nEND_GOAL_PLAN";
    return (`${originalGoalPrompt.trim()}\n\n` +
        `## Goal Planner Output\n\n${compactPlannerOutput}\n\n` +
        `Use the original objective plus this planner output to create durable Goal setup only. ` +
        `Do not redo planner research unless the planner output is unusable.`);
}
export function isGoalPromptCommandName(cmdName) {
    return getPromptCommand(cmdName)?.name === "goal";
}
export async function runGoalPromptSetupSequence({ userContent, fullPrompt, messagesRef, setGoalModeAndPrompt, runAgent, onStage, }) {
    onStage?.("GOAL PLANNER STARTED");
    await setGoalModeAndPrompt("planner");
    const plannerStartIndex = messagesRef.current.length;
    await runAgent(userContent);
    const plannerOutput = collectAssistantTextSince(messagesRef.current, plannerStartIndex);
    const setupPrompt = buildGoalSetupPromptFromPlanner({
        originalGoalPrompt: fullPrompt,
        plannerOutput,
    });
    onStage?.("GOAL PLAN CREATED -> PASSING TO SETUP AGENT");
    await setGoalModeAndPrompt("setup");
    onStage?.("GOAL SETUP AGENT STARTED");
    await runAgent(setupPrompt);
    onStage?.("GOAL SETUP COMPLETE -> OPENING GOAL PANE");
}
export async function submitPromptCommand({ trimmed, inputImages, currentModel, customCommands, setLastUserMessage, setDoneStatus, finalizeSubmittedUserItem, runAgent, setLiveItems, getId, reloadCustomCommands, messagesRef, setGoalModeAndPrompt, onGoalStage, onGoalSetupComplete, }) {
    const promptCommandRoute = routePromptCommandInput(trimmed, PROMPT_COMMANDS, customCommands);
    if (!promptCommandRoute)
        return false;
    const { cmdName, cmdArgs, fullPrompt } = promptCommandRoute;
    log("INFO", "command", `Prompt command: /${cmdName}${cmdArgs ? ` (args: ${cmdArgs})` : ""}`);
    const imageCount = inputImages.filter((img) => img.kind === "image").length;
    const videoCount = inputImages.filter((img) => img.kind === "video").length;
    const modelInfo = getModel(currentModel);
    const modelSupportsImages = modelInfo?.supportsImages ?? true;
    const modelSupportsVideo = modelInfo?.supportsVideo ?? false;
    const userContent = buildUserContentWithAttachments(fullPrompt, inputImages, modelSupportsImages, modelSupportsVideo);
    const userItem = {
        kind: "user",
        text: trimmed,
        imageCount: imageCount > 0 ? imageCount : undefined,
        videoCount: videoCount > 0 ? videoCount : undefined,
        id: getId(),
    };
    setLastUserMessage(trimmed);
    setDoneStatus(null);
    finalizeSubmittedUserItem(userItem);
    const isGoalSetupCommand = isGoalPromptCommandName(cmdName);
    try {
        if (isGoalSetupCommand && messagesRef && setGoalModeAndPrompt) {
            await runGoalPromptSetupSequence({
                userContent,
                fullPrompt,
                messagesRef,
                setGoalModeAndPrompt,
                runAgent,
                onStage: onGoalStage,
            });
            await onGoalSetupComplete?.();
        }
        else {
            await runAgent(userContent);
        }
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        log("ERROR", "error", msg);
        const isAbort = msg.includes("aborted") || msg.includes("abort");
        setLiveItems((prev) => [
            ...prev,
            isAbort
                ? { kind: "stopped", text: "Request was stopped.", id: getId() }
                : toErrorItem(err, getId()),
        ]);
    }
    finally {
        if (isGoalSetupCommand && setGoalModeAndPrompt) {
            await setGoalModeAndPrompt("off");
        }
    }
    reloadCustomCommands();
    return true;
}
//# sourceMappingURL=submit-prompt-command.js.map