const require_logger = require("./logger-DuG3amVa.cjs");
const require_fetch = require("./fetch-Hdu2Q-w3.cjs");
const require_time = require("./time-C8D2VmK1.cjs");
const require_cache = require("./cache-JYoIjHBA.cjs");
const require_dataUrl = require("./dataUrl-DxL5oIH5.cjs");
const require_util = require("./util-DtSnbKEe.cjs");
//#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 require_util.getGoogleClient({ credentials: require_util.loadCredentials(this.config.credentials) });
		return client;
	}
	async getProjectId() {
		return await require_util.resolveProjectId(this.config, this.env);
	}
	async callApi(prompt, _context) {
		if (!prompt) return { error: "Prompt is required for image generation" };
		if (this.config.projectId || require_logger.getEnvString("GOOGLE_CLOUD_PROJECT") || require_logger.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 || require_logger.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`;
			require_logger.logger.debug(`Vertex AI Image API endpoint: ${endpoint}`);
			require_logger.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: require_fetch.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`;
		require_logger.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
			}
		};
		require_logger.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 = require_util.createAuthCacheDiscriminator(headers);
			const response = await this.withRetry(() => require_cache.fetchWithCache(endpoint, {
				method: "POST",
				headers,
				body: JSON.stringify(body),
				...authDiscriminator && { _authHash: authDiscriminator }
			}, require_fetch.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) {
		require_logger.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: require_dataUrl.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") require_logger.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 || require_logger.getEnvString("GOOGLE_API_KEY") || require_logger.getEnvString("GOOGLE_GENERATIVE_AI_API_KEY") || require_logger.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);
			require_logger.logger.warn(`${operationName} failed (attempt ${attempt + 1}/${this.maxRetries}), retrying in ${delay}ms...`);
			await require_time.sleep(delay);
		}
		throw lastError;
	}
};
//#endregion
exports.GoogleImageProvider = GoogleImageProvider;

//# sourceMappingURL=image-N5ySu-xP.cjs.map