import { init_agent_scope, resolveAgentHomeDir, resolveDefaultAgentId } from "../agent-scope.js";
import { getAgentDefaultModelRef, init_schema } from "../../config/schema.js";
import { extractProfileAgentId } from "../../config/agent-profile.js";
import { getDefaultModelSync, init_providers } from "../../providers/index.js";
import { formatInboundFileTextBlock } from "../../channels/attachments/inbound-persist.js";
import { expandAtFileMentionsInPlainText } from "../context/expand-at-file-mentions.js";
import { resolveInboundImageContentParts } from "../image/inbound-image-handling.js";
//#region src/agent/service/build-direct-message-content.ts
init_schema();
init_providers();
init_agent_scope();
/**
* Build user message parts (text + resolved images/files) for direct / webchat turns.
*/
async function buildDirectUserMessageContent(opts) {
	const { content, attachments, sessionKey, config, agentManager, modelManager } = opts;
	const messageContent = [];
	const sk = sessionKey ?? "";
	if (content.trim()) {
		let textPart = content;
		if (/@file:/.test(textPart)) {
			const wsKey = sk !== "" ? sk : "agent:main:main";
			const root = agentManager.getResolvedWorkspaceForSession(wsKey);
			textPart = await expandAtFileMentionsInPlainText(textPart, root);
		}
		messageContent.push({
			type: "text",
			text: textPart
		});
	}
	if (!attachments?.length) return messageContent;
	const modelRef = sk !== "" ? modelManager.getModelForSession(sk) : getAgentDefaultModelRef(config) ?? getDefaultModelSync(config);
	const storageRoot = sk !== "" ? resolveAgentHomeDir(config, extractProfileAgentId(sk, config)) : resolveAgentHomeDir(config, resolveDefaultAgentId(config));
	let i = 0;
	while (i < attachments.length) {
		const att = attachments[i];
		if (att.type === "image" || att.type === "photo" || Boolean(att.mimeType?.startsWith("image/"))) {
			const group = [];
			while (i < attachments.length) {
				const a = attachments[i];
				if (!(a.type === "image" || a.type === "photo" || Boolean(a.mimeType?.startsWith("image/")))) break;
				if (!a.data || a.data.length === 0) {
					i += 1;
					continue;
				}
				group.push({
					data: a.data,
					mimeType: a.mimeType || "image/png"
				});
				i += 1;
			}
			if (group.length > 0) {
				const parts = await resolveInboundImageContentParts({
					modelRef: modelRef || getDefaultModelSync(config),
					cfg: config,
					userTextForContext: content.trim() ? content : "",
					images: group
				});
				messageContent.push(...parts);
			}
		} else {
			const fileBlock = formatInboundFileTextBlock(att, storageRoot);
			messageContent.push({
				type: "text",
				text: fileBlock
			});
			i += 1;
		}
	}
	return messageContent;
}
//#endregion
export { buildDirectUserMessageContent };

//# sourceMappingURL=build-direct-message-content.js.map