import { toolSessionManager } from "../services/ToolSessionManager.js";
import { getModelContextWindow } from "../../utils/model-context-utils.js";
import { getPrimaryModel } from "./model-config.js";
import { ResponseFormatter } from "../../stream/ResponseFormatter.js";

//#region src/domains/run/agents/generation/response-formatting.ts
async function formatFinalResponse(ctx, response, textResponse, sessionId, contextId) {
	let formattedContent = response.formattedContent || null;
	if (!formattedContent) {
		const session = toolSessionManager.getSession(sessionId);
		const modelContextInfo = getModelContextWindow(getPrimaryModel(ctx.config));
		const responseFormatter = new ResponseFormatter(ctx.executionContext, {
			sessionId,
			taskId: session?.taskId,
			projectId: session?.projectId,
			contextId,
			artifactComponents: ctx.artifactComponents,
			streamRequestId: ctx.streamRequestId ?? "",
			subAgentId: ctx.config.id,
			contextWindowSize: modelContextInfo.contextWindow ?? void 0
		});
		if (response.object) formattedContent = await responseFormatter.formatObjectResponse(response.object, contextId);
		else if (textResponse) formattedContent = await responseFormatter.formatResponse(textResponse, contextId);
	}
	return {
		...response,
		formattedContent
	};
}

//#endregion
export { formatFinalResponse };