import { AiGenerationState } from "@superblocksteam/library-shared/types";
import { generateText } from "ai";
import { CLARK_SUMMARY_HEADER_CONTENT } from "../../const.js";
import { traceLLM } from "../../llmobs/helpers.js";
import { LLMObsTracer } from "../../llmobs/index.js";
import { AGENT_NEEDS_USER_INPUT, V3_AGENT_FINISHED, RUNTIME_REVIEW_FINISHED, SERVICE_STARTED_WITH_DRAFT, } from "../clark-fsm.js";
import { sendUserGenerationStateChannel, sendUserMessageChannel, } from "../helpers/peer.js";
/**
 * Converts Clark context workflow metrics to AiWorkflowSummary format for submission.
 */
function createWorkflowSummary(promptId, workflowMetrics) {
    const completedAt = new Date().toISOString();
    const startedAt = workflowMetrics.workflowStartedAt;
    return {
        promptId: promptId,
        attributes: {
            tool_call_count: workflowMetrics.toolCallCount,
            step_count: workflowMetrics.stepCount,
            lines_added: workflowMetrics.linesAdded,
            lines_edited: workflowMetrics.linesEdited,
            lines_removed: workflowMetrics.linesRemoved,
            workflow_started_at: startedAt,
            workflow_completed_at: completedAt,
        },
    };
}
export const doAwaitingUser = (clark, { signals, chatSessionStore, llmProvider, clarkProfiler, }) => {
    const sendUsergenerationState = sendUserGenerationStateChannel(clark);
    const sendUserMessage = sendUserMessageChannel(clark, chatSessionStore);
    return async ({ event }) => {
        switch (event.type) {
            case AGENT_NEEDS_USER_INPUT: {
                const { hasSuggestions = false } = clark.context;
                const { advice } = event;
                clark.logger.info("[awaiting-user] AGENT_NEEDS_USER_INPUT - returning to user", {
                    hasSuggestions,
                    currentMode: clark.context.currentMode,
                    hasAdvice: !!advice,
                });
                signals.emit("generationCompleted", hasSuggestions);
                await clarkProfiler?.endSession();
                // Submit workflow summary metrics
                const { promptId, workflowMetrics } = clark.context;
                if (promptId && workflowMetrics) {
                    const submitStart = performance.now();
                    clark.logger.info("[awaiting-user] Starting submitWorkflowSummary");
                    await chatSessionStore.submitWorkflowSummary(createWorkflowSummary(promptId, workflowMetrics));
                    clark.logger.info(`[awaiting-user] submitWorkflowSummary completed in ${(performance.now() - submitStart).toFixed(2)}ms`);
                }
                if (advice) {
                    void sendUserMessage({
                        text: advice,
                    });
                }
                void sendUsergenerationState({
                    state: AiGenerationState.AWAITING_USER_INPUT,
                    hasSuggestions,
                });
                break;
            }
            case V3_AGENT_FINISHED: {
                const { hasSuggestions = false } = clark.context;
                clark.logger.info("[awaiting-user] V3_AGENT_FINISHED - returning to user, emitting generationCompleted", {
                    hasSuggestions,
                    willTriggerUpload: hasSuggestions,
                    currentMode: clark.context.currentMode,
                });
                signals.emit("generationCompleted", hasSuggestions);
                await clarkProfiler?.endSession();
                // Submit workflow summary metrics
                const { promptId, workflowMetrics } = clark.context;
                if (promptId && workflowMetrics) {
                    await chatSessionStore.submitWorkflowSummary(createWorkflowSummary(promptId, workflowMetrics));
                }
                void sendUsergenerationState({
                    state: AiGenerationState.COMPLETED,
                    hasSuggestions: true,
                });
                break;
            }
            case RUNTIME_REVIEW_FINISHED: {
                const { hasSuggestions = false, summaryMessages = [] } = clark.context;
                clark.logger.info("[awaiting-user] RUNTIME_REVIEW_FINISHED - emitting generationCompleted", {
                    hasSuggestions,
                    willTriggerUpload: hasSuggestions,
                });
                signals.emit("generationCompleted", hasSuggestions);
                await clarkProfiler?.endSession();
                // Submit workflow summary metrics
                const { promptId, workflowMetrics } = clark.context;
                if (promptId && workflowMetrics) {
                    await chatSessionStore.submitWorkflowSummary(createWorkflowSummary(promptId, workflowMetrics));
                }
                if (summaryMessages.length > 0) {
                    void sendUserMessage({
                        type: "text",
                        group: "clark",
                        text: "\n---\n",
                    });
                    void sendUserMessage({
                        type: "text",
                        group: "clark",
                        text: CLARK_SUMMARY_HEADER_CONTENT,
                    });
                    if (clark.context.usedDebugging) {
                        void sendUsergenerationState({
                            state: AiGenerationState.SUMMARIZING,
                            hasSuggestions,
                        });
                        // Start summary generation profiling
                        clarkProfiler.getProfiler().startFrame("summary_generation");
                        clarkProfiler.startLLMWaiting();
                        const finalSummary = await getFinalSummary(llmProvider, chatSessionStore, summaryMessages, clark.tracer, clark.context.abortController?.signal);
                        // End profiling spans
                        clarkProfiler.endFrame(); // End waiting_on_llm
                        clarkProfiler.endFrame(); // End summary_generation
                        void sendUserMessage({
                            text: finalSummary,
                        });
                    }
                    else {
                        for (const message of summaryMessages) {
                            void sendUserMessage({
                                text: message.content,
                            });
                        }
                    }
                }
                void sendUsergenerationState({
                    state: AiGenerationState.COMPLETED,
                    hasSuggestions,
                });
                break;
            }
            case SERVICE_STARTED_WITH_DRAFT:
                break;
            default:
                throw new Error(`Unhandled event: ${event}`);
        }
    };
};
const getFinalSummary = async (llmProvider, chatSessionStore, summaryMessages, llmobs = LLMObsTracer.instance, abortSignal) => {
    const lastUserMessage = chatSessionStore.getLastUserMessage();
    const initialMessages = summaryMessages.filter((msg) => !msg.isDebugging);
    const debuggingMessages = summaryMessages.filter((msg) => msg.isDebugging);
    const userPrompt = lastUserMessage?.content || "User request";
    const prompt = `Create a concise, human-readable summary of what was accomplished based on the following conversation from an AI assistant helping a user with their Superblocks application.

USER'S REQUEST:
"${userPrompt}"

ASSISTANT'S ACTIONS:
The messages below describe what the AI assistant did in response to the user's request. Some messages are from the initial response, and some are from debugging/fixing issues that occurred afterward.

Initial Response Messages:
${initialMessages.map((msg) => `- ${msg.content}`).join("\n")}

${debuggingMessages.length > 0
        ? `\nDebugging/Fix Messages:
${debuggingMessages.map((msg) => `- ${msg.content}`).join("\n")}`
        : ""}

Please create a BRIEF summary that:
1. Explains what was changed or accomplished in clear, non-technical language
2. Groups related changes together logically
3. If there were debugging fixes, weave these changes into the summary; do not identify them as "debugging"
4. Is written from the perspective of what was done for the user
5. Focuses on the end result rather than technical implementation details
6. CRITICAL: Matches the verbosity and tone of both the user's original request and the assistant's initial response messages - if the user was brief, keep it concise; if they were detailed, provide more context

Create a summary of what was accomplished:`;
    const model = llmProvider.modelForTask("summarizeMessages");
    const summary = await traceLLM("getFinalSummary", model.modelId, model.provider, async () => {
        return generateText({
            model,
            prompt,
            abortSignal,
        });
    }, {}, llmobs);
    return summary.text;
};
//# sourceMappingURL=awaiting-user.js.map