import { extractTextContent } from "../context/workspace.js";
import { coerceToolModelConfig } from "./tool-model-config.js";
//#region src/agent/image/image-helpers.ts
function decodeDataUrl(dataUrl) {
	const trimmed = dataUrl.trim();
	const match = /^data:([^;,]+);base64,([a-z0-9+/=\r\n]+)$/i.exec(trimmed);
	if (!match) throw new Error("Invalid data URL (expected base64 data: URL).");
	const mimeType = (match[1] ?? "").trim().toLowerCase();
	if (!mimeType.startsWith("image/")) throw new Error(`Unsupported data URL type: ${mimeType || "unknown"}`);
	const b64 = (match[2] ?? "").trim();
	const buffer = Buffer.from(b64, "base64");
	if (buffer.length === 0) throw new Error("Invalid data URL: empty payload.");
	return {
		buffer,
		mimeType,
		kind: "image"
	};
}
function coerceImageAssistantText(params) {
	const stop = params.message.stopReason;
	const errorMessage = params.message.errorMessage?.trim();
	if (stop === "error" || stop === "aborted") throw new Error(errorMessage ? `Image model failed (${params.provider}/${params.model}): ${errorMessage}` : `Image model failed (${params.provider}/${params.model})`);
	if (errorMessage) throw new Error(`Image model failed (${params.provider}/${params.model}): ${errorMessage}`);
	const text = extractTextContent(params.message.content);
	if (text.trim()) return text.trim();
	throw new Error(`Image model returned no text (${params.provider}/${params.model}).`);
}
function coerceImageModelConfig(cfg) {
	return coerceToolModelConfig(cfg?.agents?.defaults?.imageModel);
}
function applyImageGenerationModelConfigDefaults(cfg, imageGenerationModelConfig) {
	if (!cfg) return;
	const primary = imageGenerationModelConfig.primary?.trim();
	if (!primary) return cfg;
	return {
		...cfg,
		agents: {
			...cfg.agents,
			defaults: {
				...cfg.agents?.defaults,
				imageGenerationModel: {
					primary,
					...imageGenerationModelConfig.fallbacks?.length ? { fallbacks: imageGenerationModelConfig.fallbacks } : {}
				}
			}
		}
	};
}
function resolvePromptAndModelOverride(args, defaultPrompt) {
	return {
		prompt: typeof args.prompt === "string" && args.prompt.trim() ? args.prompt.trim() : defaultPrompt,
		modelOverride: typeof args.model === "string" && args.model.trim() ? args.model.trim() : void 0
	};
}
function buildImageToolTextResult(result, extraDetails) {
	return {
		content: [{
			type: "text",
			text: result.text
		}],
		details: {
			model: `${result.provider}/${result.model}`,
			...extraDetails,
			attempts: result.attempts
		}
	};
}
//#endregion
export { applyImageGenerationModelConfigDefaults, buildImageToolTextResult, coerceImageAssistantText, coerceImageModelConfig, decodeDataUrl, resolvePromptAndModelOverride };

//# sourceMappingURL=image-helpers.js.map