import { AuthError, FatalError, QuotaExhaustedError, RateLimitError, TransientError, setAdapterFactories } from "./index.js";
//#region src/google.ts
function extractGeminiSystem(messages) {
	const systemParts = messages.filter((m) => m.role === "system").map((m) => typeof m.content === "string" ? m.content : m.content.filter((b) => b.type === "text").map((b) => b.text).join(""));
	return systemParts.length > 0 ? systemParts.join("\n\n") : void 0;
}
function mapContentToGemini(content) {
	if (typeof content === "string") return content;
	return content.map((block) => {
		if (block.type === "text") return { text: block.text };
		const img = block.image;
		return { inlineData: {
			mimeType: img.mediaType,
			data: img.data
		} };
	});
}
function mapMessagesToGemini(messages) {
	return messages.filter((m) => m.role !== "system").map((message) => {
		const mapped = mapContentToGemini(message.content);
		const parts = typeof mapped === "string" ? [{ text: mapped }] : mapped;
		return {
			role: message.role === "assistant" ? "model" : "user",
			parts
		};
	});
}
function mapGeminiResponse(body, provider, model) {
	return {
		content: body.text?.trim() ?? "",
		model,
		provider,
		usage: {
			promptTokens: body.usageMetadata?.promptTokenCount ?? 0,
			completionTokens: body.usageMetadata?.candidatesTokenCount ?? 0
		},
		finishReason: void 0
	};
}
function classifyGoogleError(status, message, provider) {
	if (status === 429) {
		if (/RESOURCE_EXHAUSTED|quota/i.test(message)) return new QuotaExhaustedError(message, provider);
		return new RateLimitError(message, provider);
	}
	if (status === 401 || status === 403) return new AuthError(message, provider);
	if (status !== void 0 && status >= 500) return new TransientError(message, provider);
	return new FatalError(message, provider);
}
function mapSdkError(err, provider) {
	const status = err.status;
	const code = err.code;
	const msg = err.message ?? String(err);
	if (status === 429) {
		if (/RESOURCE_EXHAUSTED|quota/i.test(msg)) throw new QuotaExhaustedError(msg, provider);
		throw new RateLimitError(msg, provider);
	}
	if (status === 401 || status === 403) throw new AuthError(msg, provider);
	if (code === "ECONNRESET" || code === "ETIMEDOUT" || code === "ENOTFOUND" || status !== void 0 && status >= 500) throw new TransientError(msg, provider);
	throw classifyGoogleError(status, msg, provider);
}
async function createGoogleClient(creds) {
	if (creds.createClient) return creds.createClient(creds.apiKey);
	const { GoogleGenAI } = await import("@google/genai");
	return new GoogleGenAI({ apiKey: creds.apiKey });
}
function makeGoogleAdapter(creds) {
	return {
		provider: "google",
		supportsImage: true,
		async call(req) {
			const client = await createGoogleClient(creds);
			const system = extractGeminiSystem(req.messages);
			const contents = mapMessagesToGemini(req.messages);
			try {
				return mapGeminiResponse(await client.models.generateContent({
					model: req.model,
					contents,
					config: {
						...system ? { systemInstruction: system } : {},
						...req.maxTokens !== void 0 ? { maxOutputTokens: req.maxTokens } : {},
						...req.temperature !== void 0 ? { temperature: req.temperature } : {},
						...req.stop !== void 0 ? { stopSequences: Array.isArray(req.stop) ? req.stop : [req.stop] } : {}
					}
				}), "google", req.model);
			} catch (err) {
				mapSdkError(err, "google");
			}
		}
	};
}
/** Register the google adapter factory with core `getAdapter`. */
function registerGoogleAdapter() {
	setAdapterFactories({ google: (creds) => makeGoogleAdapter(creds) });
}
//#endregion
export { classifyGoogleError, extractGeminiSystem, makeGoogleAdapter, mapContentToGemini, mapGeminiResponse, mapMessagesToGemini, registerGoogleAdapter };
