import { A as getEnvString, o as logger } from "./logger-CfDSdx1q.js";
import { w as getRequestTimeoutMs } from "./fetch-CHx36OdV.js";
import { n as sleep } from "./time-DpwT58mY.js";
import { r as fetchWithCache } from "./cache-IpWZkF7H.js";
import { i as toDataUri } from "./dataUrl-CXQl71ri.js";
import { D as resolveProjectId, E as loadCredentials, r as createAuthCacheDiscriminator, w as getGoogleClient } from "./util-BtjL1MRK.js";
//#region src/providers/google/image.ts
var GoogleImageProvider = class {
	modelName;
	config;
	env;
	maxRetries = 3;
	baseRetryDelay = 1e3;
	constructor(modelName, options = {}) {
		this.modelName = modelName;
		this.config = options.config || {};
		this.env = options.env;
	}
	id() {
		return `google:image:${this.modelName}`;
	}
	toString() {
		return `[Google Image Generation Provider ${this.modelName}]`;
	}
	/**
	* Helper method to get Google client with credentials support
	*/
	async getClientWithCredentials() {
		const { client } = await getGoogleClient({ credentials: loadCredentials(this.config.credentials) });
		return client;
	}
	async getProjectId() {
		return await resolveProjectId(this.config, this.env);
	}
	async callApi(prompt, _context) {
		if (!prompt) return { error: "Prompt is required for image generation" };
		if (this.config.projectId || getEnvString("GOOGLE_CLOUD_PROJECT") || getEnvString("GOOGLE_PROJECT_ID") || this.env?.GOOGLE_CLOUD_PROJECT || this.env?.GOOGLE_PROJECT_ID) return this.callVertexApi(prompt);
		if (this.getApiKey()) return this.callGeminiApi(prompt);
		return { error: "Imagen models require either:\n1. Google AI Studio: Set GOOGLE_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, or GEMINI_API_KEY environment variable\n2. Vertex AI: Set GOOGLE_CLOUD_PROJECT environment variable or provide projectId in config, and run \"gcloud auth application-default login\"" };
	}
	async callVertexApi(prompt) {
		const location = this.config.region || getEnvString("GOOGLE_LOCATION") || this.env?.GOOGLE_LOCATION || "us-central1";
		try {
			const client = await this.getClientWithCredentials();
			const projectId = await this.getProjectId();
			if (!projectId) return { error: "Google project ID is required for Vertex AI. Set GOOGLE_PROJECT_ID or add projectId to provider config." };
			const modelPath = this.getModelPath();
			const endpoint = `https://${location}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${location}/publishers/google/models/${modelPath}:predict`;
			logger.debug(`Vertex AI Image API endpoint: ${endpoint}`);
			logger.debug(`Project ID: ${projectId}, Location: ${location}, Model: ${modelPath}`);
			const body = {
				instances: [{ prompt: prompt.trim() }],
				parameters: {
					sampleCount: this.config.n || 1,
					aspectRatio: this.config.aspectRatio || "1:1",
					personGeneration: this.config.personGeneration || "allow_all",
					safetySetting: this.config.safetyFilterLevel || "block_some",
					addWatermark: this.config.addWatermark !== false,
					...this.config.seed !== void 0 && this.config.addWatermark === false && { seed: this.config.seed }
				}
			};
			const startTime = Date.now();
			const response = await this.withRetry(() => client.request({
				url: endpoint,
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					...this.config.headers || {}
				},
				data: body,
				timeout: getRequestTimeoutMs()
			}), "Vertex AI API call");
			const latencyMs = Date.now() - startTime;
			return this.processResponse(response.data, false, latencyMs);
		} catch (err) {
			if (err.response?.data?.error) return { error: `Vertex AI error: ${err.response.data.error.message || "Unknown error"}` };
			return { error: `Failed to call Vertex AI: ${err.message || "Unknown error"}` };
		}
	}
	async callGeminiApi(prompt) {
		const apiKey = this.getApiKey();
		if (!apiKey) return { error: "API key not found. Set GOOGLE_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, or GEMINI_API_KEY environment variable." };
		const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${this.getModelPath()}:predict`;
		logger.debug(`Google AI Studio Image API endpoint: ${endpoint}`);
		const safetySetting = this.mapSafetyLevelForGemini(this.config.safetyFilterLevel);
		const body = {
			instances: [{ prompt: prompt.trim() }],
			parameters: {
				sampleCount: this.config.n || 1,
				aspectRatio: this.config.aspectRatio || "1:1",
				personGeneration: this.config.personGeneration || "allow_all",
				safetySetting
			}
		};
		logger.debug(`Making request to ${endpoint} with API key`);
		try {
			const headers = {
				"Content-Type": "application/json",
				"x-goog-api-key": apiKey,
				...this.config.headers || {}
			};
			const authDiscriminator = createAuthCacheDiscriminator(headers);
			const response = await this.withRetry(() => fetchWithCache(endpoint, {
				method: "POST",
				headers,
				body: JSON.stringify(body),
				...authDiscriminator && { _authHash: authDiscriminator }
			}, getRequestTimeoutMs(), "json"), "Google AI Studio API call");
			return this.processResponse(response.data, response.cached, response.latencyMs);
		} catch (err) {
			return { error: `API call error: ${String(err)}` };
		}
	}
	processResponse(data, cached, latencyMs) {
		logger.debug(`Response data: ${JSON.stringify(data).substring(0, 200)}...`);
		if (!data || typeof data !== "object") return { error: "Invalid response from API" };
		if (data.error) return { error: data.error.message || JSON.stringify(data.error) };
		if (!data.predictions || data.predictions.length === 0) return { error: "No images generated" };
		const imageOutputs = [];
		let totalCost = 0;
		const costPerImage = this.getCost();
		for (const prediction of data.predictions) {
			const imageData = prediction.image || prediction;
			const base64Image = imageData.bytesBase64Encoded;
			const mimeType = imageData.mimeType || "image/png";
			if (base64Image) {
				imageOutputs.push({
					data: toDataUri(mimeType, base64Image),
					mimeType
				});
				totalCost += costPerImage;
			}
		}
		if (imageOutputs.length === 0) return { error: "No valid images generated" };
		return {
			output: imageOutputs[0].data,
			images: imageOutputs,
			cached,
			latencyMs,
			cost: totalCost
		};
	}
	mapSafetyLevelForGemini(level) {
		if (level && level !== "block_low_and_above") logger.warn(`Google AI Studio only supports 'block_low_and_above' safety setting. Requested setting '${level}' will be overridden.`);
		return "block_low_and_above";
	}
	getApiKey() {
		return this.config.apiKey || getEnvString("GOOGLE_API_KEY") || getEnvString("GOOGLE_GENERATIVE_AI_API_KEY") || getEnvString("GEMINI_API_KEY") || this.env?.GOOGLE_API_KEY || this.env?.GOOGLE_GENERATIVE_AI_API_KEY || this.env?.GEMINI_API_KEY;
	}
	getModelPath() {
		if (this.modelName.startsWith("imagen-")) return this.modelName;
		return `imagen-${this.modelName}`;
	}
	getCost() {
		return {
			"imagen-4.0-ultra-generate-preview-06-06": .06,
			"imagen-4.0-generate-preview-06-06": .04,
			"imagen-4.0-fast-generate-preview-06-06": .02,
			"imagen-3.0-generate-002": .04,
			"imagen-3.0-generate-001": .04,
			"imagen-3.0-fast-generate-001": .02
		}[this.getModelPath()] || .04;
	}
	async withRetry(operation, operationName) {
		let lastError;
		for (let attempt = 0; attempt < this.maxRetries; attempt++) try {
			return await operation();
		} catch (error) {
			lastError = error;
			if (error.response?.status >= 400 && error.response?.status < 500) throw error;
			if (attempt === this.maxRetries - 1) throw error;
			const delay = this.baseRetryDelay * Math.pow(2, attempt);
			logger.warn(`${operationName} failed (attempt ${attempt + 1}/${this.maxRetries}), retrying in ${delay}ms...`);
			await sleep(delay);
		}
		throw lastError;
	}
};
//#endregion
export { GoogleImageProvider };

//# sourceMappingURL=image-DQ--11hq.js.map