import { getApiKey, init_providers, resolveModel } from "../../../providers/index.js";
import { registerImageUnderstandingProvider } from "./provider-registry.js";
import { coerceImageAssistantText } from "../image-helpers.js";
import { complete } from "@earendil-works/pi-ai";
//#region src/agent/image/understanding/pi-ai-provider.ts
init_providers();
function resolveMaxTokens(modelMaxTokens, requestedMaxTokens = 4096) {
	if (typeof modelMaxTokens !== "number" || !Number.isFinite(modelMaxTokens) || modelMaxTokens <= 0) return requestedMaxTokens;
	return Math.min(requestedMaxTokens, modelMaxTokens);
}
function buildPiAiImageUnderstandingProvider(providerId) {
	return {
		id: providerId,
		label: `pi-ai (${providerId})`,
		async isConfigured() {
			const apiKey = await getApiKey(providerId);
			return Boolean(apiKey);
		},
		async describeImages(modelId, request) {
			const modelRef = `${providerId}/${modelId}`;
			const model = resolveModel(modelRef);
			if (!model.input?.includes("image")) throw new Error(`Model does not support images: ${modelRef}`);
			const apiKey = await getApiKey(providerId);
			if (!apiKey) throw new Error(`No API key configured for provider: ${providerId}`);
			const context = { messages: [{
				role: "user",
				content: [{
					type: "text",
					text: request.prompt
				}, ...request.images.map((img) => ({
					type: "image",
					data: img.buffer.toString("base64"),
					mimeType: img.mimeType || "image/jpeg"
				}))],
				timestamp: Date.now()
			}] };
			const maxTokens = resolveMaxTokens(model.maxTokens, request.maxTokens ?? 512);
			const timeoutMs = request.timeoutMs ?? 6e4;
			const timeoutSignal = typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(timeoutMs) : void 0;
			return {
				text: coerceImageAssistantText({
					message: await complete(model, context, {
						apiKey,
						maxTokens,
						signal: (() => {
							if (timeoutSignal && request.signal && typeof AbortSignal.any === "function") return AbortSignal.any([request.signal, timeoutSignal]);
							if (request.signal) return request.signal;
							if (timeoutSignal) return timeoutSignal;
							const controller = new AbortController();
							setTimeout(() => controller.abort(), timeoutMs);
							return controller.signal;
						})()
					}),
					provider: providerId,
					model: modelId
				}),
				provider: providerId,
				model: modelId
			};
		}
	};
}
for (const providerId of [
	"openai",
	"anthropic",
	"google"
]) registerImageUnderstandingProvider(buildPiAiImageUnderstandingProvider(providerId));
//#endregion
export { buildPiAiImageUnderstandingProvider };

//# sourceMappingURL=pi-ai-provider.js.map