import { normalizeBaseUrl, postMultipartRequest } from "../media-shared/http/provider-http.js";
import "../media-shared/http/index.js";
import { registerMediaUnderstandingProvider } from "./registry.js";
import path from "node:path";
//#region src/media-understanding/openai-compatible-audio.ts
/**
* OpenAI-compatible `/audio/transcriptions` helper for STT providers and extensions.
*/
function resolveAudioTranscriptionUploadFileName(fileName, mime) {
	const trimmed = fileName?.trim();
	const baseName = trimmed ? path.basename(trimmed) : "audio";
	const lowerMime = mime?.trim().toLowerCase();
	if (/\.aac$/i.test(baseName)) return `${baseName.slice(0, -4) || "audio"}.m4a`;
	if (!path.extname(baseName) && lowerMime === "audio/aac") return `${baseName || "audio"}.m4a`;
	return baseName;
}
function buildAudioTranscriptionFormData(params) {
	const form = new FormData();
	const bytes = new Uint8Array(params.buffer);
	const blob = new Blob([bytes], { type: params.mime ?? "application/octet-stream" });
	form.append("file", blob, resolveAudioTranscriptionUploadFileName(params.fileName, params.mime));
	for (const [name, value] of Object.entries(params.fields ?? {})) {
		const text = typeof value === "string" ? value.trim() : value == null ? "" : String(value);
		if (text) form.append(name, text);
	}
	return form;
}
function resolveModel(model, fallback) {
	return model?.trim() || fallback;
}
function requireTranscriptionText(text, message) {
	const trimmed = text?.trim();
	if (!trimmed) throw new Error(message);
	return trimmed;
}
async function transcribeOpenAiCompatibleAudio(params) {
	const url = `${normalizeBaseUrl(params.baseUrl ?? params.defaultBaseUrl)}/audio/transcriptions`;
	const model = resolveModel(params.model, params.defaultModel);
	const headers = {
		authorization: `Bearer ${params.apiKey}`,
		...params.headers ?? {}
	};
	const form = buildAudioTranscriptionFormData({
		buffer: params.buffer,
		fileName: params.fileName,
		mime: params.mime,
		fields: {
			model,
			language: params.language,
			prompt: params.prompt
		}
	});
	return {
		text: requireTranscriptionText((await (await postMultipartRequest(url, {
			timeoutMs: params.timeoutMs,
			label: params.label ?? `${params.provider ?? "openai"} STT`,
			headers,
			body: form
		})).json()).text, "Audio transcription response missing text"),
		model
	};
}
/** Factory for OpenAI `/audio/transcriptions`-compatible STT extension providers. */
function createOpenAiCompatibleAudioProvider(options) {
	return {
		id: options.id,
		aliases: options.aliases,
		capabilities: ["audio"],
		envKey: options.envKey,
		defaultModels: { audio: options.defaultModel },
		autoPriority: { audio: options.autoPriority ?? 50 },
		transcribeAudio: (req) => {
			if (!req.apiKey) throw new Error(`${options.label ?? options.id} STT API key missing`);
			return transcribeOpenAiCompatibleAudio({
				...req,
				defaultBaseUrl: options.defaultBaseUrl,
				defaultModel: options.defaultModel,
				provider: options.id,
				label: options.label
			});
		}
	};
}
function registerOpenAiCompatibleAudioProvider(options) {
	return registerMediaUnderstandingProvider(createOpenAiCompatibleAudioProvider(options));
}
//#endregion
export { buildAudioTranscriptionFormData, createOpenAiCompatibleAudioProvider, registerOpenAiCompatibleAudioProvider, resolveAudioTranscriptionUploadFileName, transcribeOpenAiCompatibleAudio };

//# sourceMappingURL=openai-compatible-audio.js.map