const require_helpers = require('./helpers.cjs');
const require_router = require('./router.cjs');
const require_sse_writer = require('./sse-writer.cjs');
const require_chaos = require('./chaos.cjs');
const require_recorder = require('./recorder.cjs');

//#region src/gemini-embeddings.ts
const DEFAULT_GEMINI_EMBEDDING_DIMENSIONS = 768;
async function handleGeminiEmbedContent(req, res, raw, model, fixtures, journal, defaults, setCorsHeaders, providerKey = "gemini") {
	const { logger } = defaults;
	setCorsHeaders(res);
	let embedReq;
	try {
		embedReq = JSON.parse(raw);
	} catch (parseErr) {
		const detail = parseErr instanceof Error ? parseErr.message : "unknown";
		journal.add({
			method: req.method ?? "POST",
			path: req.url ?? `/v1beta/models/${model}:embedContent`,
			headers: require_helpers.flattenHeaders(req.headers),
			body: null,
			response: {
				status: 400,
				fixture: null
			}
		});
		require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
			message: `Malformed JSON body: ${detail}`,
			code: 400,
			status: "INVALID_ARGUMENT"
		} }));
		return;
	}
	const inputText = (embedReq.content?.parts ?? []).filter((p) => p.text !== void 0).map((p) => p.text).join(" ");
	const syntheticReq = {
		model: embedReq.model ?? model,
		messages: [],
		embeddingInput: inputText,
		_endpointType: "embedding",
		_context: require_helpers.getContext(req)
	};
	const testId = require_helpers.getTestId(req);
	const { fixture, skippedBySequenceOrTurn } = require_router.matchFixtureDiagnostic(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
	const path = req.url ?? `/v1beta/models/${model}:embedContent`;
	if (fixture) {
		journal.incrementFixtureMatchCount(fixture, fixtures, testId);
		logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);
	} else logger.debug(`No fixture matched for request`);
	if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, journal, {
		method: req.method ?? "POST",
		path,
		headers: require_helpers.flattenHeaders(req.headers),
		body: syntheticReq
	}, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) return;
	if (fixture) {
		const response = await require_helpers.resolveResponse(fixture, syntheticReq);
		if (require_helpers.isErrorResponse(response)) {
			const status = response.status ?? 500;
			journal.add({
				method: req.method ?? "POST",
				path,
				headers: require_helpers.flattenHeaders(req.headers),
				body: syntheticReq,
				response: {
					status,
					fixture
				}
			});
			const geminiError = { error: {
				code: status,
				message: response.error.message,
				status: response.error.type ?? "ERROR"
			} };
			require_sse_writer.writeErrorResponse(res, status, JSON.stringify(geminiError), { retryAfter: response.retryAfter });
			return;
		}
		if (require_helpers.isEmbeddingResponse(response)) {
			journal.add({
				method: req.method ?? "POST",
				path,
				headers: require_helpers.flattenHeaders(req.headers),
				body: syntheticReq,
				response: {
					status: 200,
					fixture
				}
			});
			const body = { embedding: { values: [...response.embedding] } };
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify(body));
			return;
		}
		journal.add({
			method: req.method ?? "POST",
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status: 500,
				fixture
			}
		});
		require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
			message: "Fixture response did not match any known embedding type (must have embedding or error)",
			code: 500,
			status: "INTERNAL"
		} }));
		return;
	}
	if (require_helpers.resolveStrictMode(defaults.strict, req.headers)) {
		const strictMessage = require_helpers.strictNoMatchMessage(skippedBySequenceOrTurn);
		logger.error(require_helpers.strictNoMatchLogLine(req.method ?? "POST", path, skippedBySequenceOrTurn));
		journal.add({
			method: req.method ?? "POST",
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status: 503,
				fixture: null,
				...require_helpers.strictOverrideField(defaults.strict, req.headers)
			}
		});
		require_sse_writer.writeErrorResponse(res, 503, JSON.stringify({ error: {
			message: strictMessage,
			code: 503,
			status: "UNAVAILABLE"
		} }));
		return;
	}
	if (defaults.record) {
		const outcome = await require_recorder.proxyAndRecord(req, res, syntheticReq, providerKey, path, fixtures, defaults, raw);
		if (outcome === "handled_by_hook") return;
		if (outcome !== "not_configured") {
			journal.add({
				method: req.method ?? "POST",
				path,
				headers: require_helpers.flattenHeaders(req.headers),
				body: syntheticReq,
				response: {
					status: res.statusCode ?? 200,
					fixture: null,
					source: "proxy"
				}
			});
			return;
		}
	}
	const embedding = require_helpers.generateDeterministicEmbedding(inputText, embedReq.outputDimensionality ?? DEFAULT_GEMINI_EMBEDDING_DIMENSIONS);
	logger.warn(`No embedding fixture matched for "${inputText.slice(0, 80)}" — returning deterministic fallback`);
	journal.add({
		method: req.method ?? "POST",
		path,
		headers: require_helpers.flattenHeaders(req.headers),
		body: syntheticReq,
		response: {
			status: 200,
			fixture: null
		}
	});
	const body = { embedding: { values: embedding } };
	res.writeHead(200, { "Content-Type": "application/json" });
	res.end(JSON.stringify(body));
}

//#endregion
exports.handleGeminiEmbedContent = handleGeminiEmbedContent;
//# sourceMappingURL=gemini-embeddings.cjs.map