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/elevenlabs-audio.ts
async function handleElevenLabsTTS(req, res, body, fixtures, defaults, journal, voiceId) {
	const path = req.url ?? `/v1/text-to-speech/${voiceId}`;
	const method = req.method ?? "POST";
	let parsed;
	try {
		parsed = JSON.parse(body);
	} catch (parseErr) {
		const detail = parseErr instanceof Error ? parseErr.message : "unknown";
		journal.add({
			method,
			path,
			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: ${detail}`,
			type: "invalid_request_error",
			code: "invalid_json"
		} }));
		return;
	}
	const promptText = typeof parsed.text === "string" && parsed.text ? parsed.text : void 0;
	const syntheticReq = {
		model: parsed.model_id ?? "eleven_multilingual_v2",
		messages: [{
			role: "user",
			content: promptText ?? ""
		}],
		_endpointType: "elevenlabs-tts",
		_context: require_helpers.getContext(req)
	};
	if (!promptText) {
		journal.add({
			method,
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status: 400,
				fixture: null
			}
		});
		require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
			message: "Missing required parameter: 'text'",
			type: "invalid_request_error"
		} }));
		return;
	}
	const testId = require_helpers.getTestId(req);
	const { fixture, skippedBySequenceOrTurn } = require_router.matchFixtureDiagnostic(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
	if (fixture) journal.incrementFixtureMatchCount(fixture, fixtures, testId);
	if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, journal, {
		method,
		path,
		headers: require_helpers.flattenHeaders(req.headers),
		body: syntheticReq
	}, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) return;
	if (!fixture) {
		if (require_helpers.resolveStrictMode(defaults.strict, req.headers)) {
			const strictMessage = require_helpers.strictNoMatchMessage(skippedBySequenceOrTurn);
			defaults.logger.error(require_helpers.strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));
			journal.add({
				method,
				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,
				type: "invalid_request_error",
				code: "no_fixture_match"
			} }));
			return;
		}
		if (defaults.record) {
			const outcome = await require_recorder.proxyAndRecord(req, res, syntheticReq, "elevenlabs", req.url ?? `/v1/text-to-speech/${voiceId}`, fixtures, defaults, body);
			if (outcome === "handled_by_hook") return;
			if (outcome !== "not_configured") {
				journal.add({
					method,
					path,
					headers: require_helpers.flattenHeaders(req.headers),
					body: syntheticReq,
					response: {
						status: res.statusCode ?? 200,
						fixture: null,
						source: "proxy"
					}
				});
				return;
			}
		}
		journal.add({
			method,
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status: 404,
				fixture: null,
				...require_helpers.strictOverrideField(defaults.strict, req.headers)
			}
		});
		require_sse_writer.writeErrorResponse(res, 404, JSON.stringify({ error: {
			message: "No fixture matched",
			type: "invalid_request_error",
			code: "no_fixture_match"
		} }));
		return;
	}
	const response = await require_helpers.resolveResponse(fixture, syntheticReq);
	if (require_helpers.isErrorResponse(response)) {
		const status = response.status ?? 500;
		journal.add({
			method,
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status,
				fixture
			}
		});
		require_sse_writer.writeErrorResponse(res, status, require_helpers.serializeErrorResponse(response), { retryAfter: response.retryAfter });
		return;
	}
	if (!require_helpers.isAudioResponse(response)) {
		journal.add({
			method,
			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 is not an audio type",
			type: "server_error"
		} }));
		return;
	}
	let audioBytes;
	let contentType;
	if (typeof response.audio === "string") {
		audioBytes = Buffer.from(response.audio, "base64");
		contentType = require_helpers.FORMAT_TO_CONTENT_TYPE[response.format ?? "mp3"] ?? "audio/mpeg";
	} else {
		audioBytes = Buffer.from(response.audio.b64Json, "base64");
		contentType = response.audio.contentType ?? "audio/mpeg";
	}
	journal.add({
		method,
		path,
		headers: require_helpers.flattenHeaders(req.headers),
		body: syntheticReq,
		response: {
			status: 200,
			fixture
		}
	});
	res.writeHead(200, { "Content-Type": contentType });
	res.end(audioBytes);
}
async function handleElevenLabsAudio(req, res, body, fixtures, defaults, journal, subType) {
	const path = req.url ?? "/v1/sound-generation";
	const method = req.method ?? "POST";
	let parsed;
	try {
		parsed = JSON.parse(body);
	} catch (parseErr) {
		const detail = parseErr instanceof Error ? parseErr.message : "unknown";
		journal.add({
			method,
			path,
			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: ${detail}`,
			type: "invalid_request_error",
			code: "invalid_json"
		} }));
		return;
	}
	let promptText;
	if (subType === "sound-generation") {
		if (typeof parsed.text === "string" && parsed.text) promptText = parsed.text;
	} else if (typeof parsed.prompt === "string" && parsed.prompt) promptText = parsed.prompt;
	else if (parsed.composition_plan != null) promptText = typeof parsed.composition_plan === "string" ? parsed.composition_plan : JSON.stringify(parsed.composition_plan);
	const syntheticReq = {
		model: parsed.model_id ?? (subType === "sound-generation" ? "eleven_text_to_sound_v2" : "music_v1"),
		messages: [{
			role: "user",
			content: promptText ?? ""
		}],
		_endpointType: "audio-gen",
		_context: require_helpers.getContext(req)
	};
	if (!promptText) {
		const field = subType === "sound-generation" ? "text" : "prompt";
		journal.add({
			method,
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status: 400,
				fixture: null
			}
		});
		require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
			message: `Missing required parameter: '${field}'`,
			type: "invalid_request_error"
		} }));
		return;
	}
	const testId = require_helpers.getTestId(req);
	const { fixture, skippedBySequenceOrTurn } = require_router.matchFixtureDiagnostic(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
	if (fixture) journal.incrementFixtureMatchCount(fixture, fixtures, testId);
	if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, journal, {
		method,
		path,
		headers: require_helpers.flattenHeaders(req.headers),
		body: syntheticReq
	}, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) return;
	if (!fixture) {
		if (require_helpers.resolveStrictMode(defaults.strict, req.headers)) {
			const strictMessage = require_helpers.strictNoMatchMessage(skippedBySequenceOrTurn);
			defaults.logger.error(require_helpers.strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));
			journal.add({
				method,
				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,
				type: "invalid_request_error",
				code: "no_fixture_match"
			} }));
			return;
		}
		if (defaults.record) {
			const outcome = await require_recorder.proxyAndRecord(req, res, syntheticReq, "elevenlabs", req.url ?? "/v1/sound-generation", fixtures, defaults, body);
			if (outcome === "handled_by_hook") return;
			if (outcome !== "not_configured") {
				journal.add({
					method,
					path,
					headers: require_helpers.flattenHeaders(req.headers),
					body: syntheticReq,
					response: {
						status: res.statusCode ?? 200,
						fixture: null,
						source: "proxy"
					}
				});
				return;
			}
		}
		journal.add({
			method,
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status: 404,
				fixture: null,
				...require_helpers.strictOverrideField(defaults.strict, req.headers)
			}
		});
		require_sse_writer.writeErrorResponse(res, 404, JSON.stringify({ error: {
			message: "No fixture matched",
			type: "invalid_request_error",
			code: "no_fixture_match"
		} }));
		return;
	}
	const response = await require_helpers.resolveResponse(fixture, syntheticReq);
	if (require_helpers.isErrorResponse(response)) {
		const status = response.status ?? 500;
		journal.add({
			method,
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status,
				fixture
			}
		});
		require_sse_writer.writeErrorResponse(res, status, require_helpers.serializeErrorResponse(response), { retryAfter: response.retryAfter });
		return;
	}
	if (subType === "plan") {
		if (!require_helpers.isTextResponse(response)) {
			journal.add({
				method,
				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 is not a text type for plan endpoint",
				type: "server_error"
			} }));
			return;
		}
		journal.add({
			method,
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status: 200,
				fixture
			}
		});
		res.writeHead(200, { "Content-Type": "application/json" });
		res.end(response.content);
		return;
	}
	if (!require_helpers.isAudioResponse(response)) {
		journal.add({
			method,
			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 is not an audio type",
			type: "server_error"
		} }));
		return;
	}
	let audioBytes;
	let contentType;
	if (typeof response.audio === "string") {
		audioBytes = Buffer.from(response.audio, "base64");
		contentType = require_helpers.FORMAT_TO_CONTENT_TYPE[response.format ?? "mp3"] ?? "audio/mpeg";
	} else {
		audioBytes = Buffer.from(response.audio.b64Json, "base64");
		contentType = response.audio.contentType ?? "audio/mpeg";
	}
	if (subType === "music" || subType === "stream") res.setHeader("song-id", "mock-song-" + Date.now());
	if (subType === "stream") {
		journal.add({
			method,
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: syntheticReq,
			response: {
				status: 200,
				fixture
			}
		});
		res.writeHead(200, {
			"Content-Type": contentType,
			"Transfer-Encoding": "chunked"
		});
		res.end(audioBytes);
		return;
	}
	journal.add({
		method,
		path,
		headers: require_helpers.flattenHeaders(req.headers),
		body: syntheticReq,
		response: {
			status: 200,
			fixture
		}
	});
	res.writeHead(200, { "Content-Type": contentType });
	res.end(audioBytes);
}

//#endregion
exports.handleElevenLabsAudio = handleElevenLabsAudio;
exports.handleElevenLabsTTS = handleElevenLabsTTS;
//# sourceMappingURL=elevenlabs-audio.cjs.map