import { createLogger } from "../../../utils/logger/index.js";
import { init_logger } from "../../../utils/logger.js";
import { registerMediaUnderstandingProvider } from "../../../media-understanding/registry.js";
import OpenAI from "openai";
//#region src/voice/stt/providers/openai-transcription.ts
/**
* OpenAI Whisper STT — implements MediaUnderstandingProvider.transcribeAudio.
*
* Uses the official `openai` SDK rather than the raw HTTP path because the SDK
* already handles multipart/form-data encoding (`file` field), streaming
* response normalization, and per-call apiKey override via constructor
* injection. The media-shared HTTP layer is intentionally not used here so we
* keep parity with the SDK's own fetch (proxy support, retries, etc.); the
* only egress is api.openai.com which is HTTPS-only and public.
*
* Streaming transcription is not implemented (Whisper returns a final text
* blob). Self-registers with `capabilities: ['audio']` only — the registry's
* `listProvidersForCapability` filter skips this provider for image/video.
*/
init_logger();
const log = createLogger("STT:OpenAI");
const DEFAULT_MODEL = "whisper-1";
async function transcribeAudio(req) {
	const startTime = Date.now();
	const model = req.model ?? DEFAULT_MODEL;
	const client = new OpenAI({
		apiKey: req.apiKey,
		...req.baseUrl ? { baseURL: req.baseUrl } : {},
		...req.headers ? { defaultHeaders: req.headers } : {}
	});
	const uint8Array = new Uint8Array(req.buffer.buffer, req.buffer.byteOffset, req.buffer.byteLength);
	const blob = new Blob([uint8Array], { type: req.mime ?? "audio/ogg" });
	log.debug({
		model,
		bufferSize: req.buffer.length,
		language: req.language,
		fileName: req.fileName
	}, "Sending to OpenAI Whisper");
	try {
		const result = await client.audio.transcriptions.create({
			file: blob,
			model,
			...req.language ? { language: req.language } : {},
			...req.prompt ? { prompt: req.prompt } : {},
			response_format: "json"
		});
		const durationSeconds = (Date.now() - startTime) / 1e3;
		log.info({
			provider: "openai",
			durationSeconds,
			textLength: result.text?.length ?? 0
		}, "Transcription completed");
		return {
			text: result.text || "",
			model,
			...req.language ? { language: req.language } : {},
			durationSeconds
		};
	} catch (error) {
		const errorMsg = error instanceof Error ? error.message : String(error);
		log.error({
			err: error,
			bufferSize: req.buffer.length,
			model
		}, `OpenAI transcription failed: ${errorMsg}`);
		throw new Error(`OpenAI STT failed: ${errorMsg}`);
	}
}
const openAiTranscriptionProvider = {
	id: "openai",
	capabilities: ["audio"],
	envKey: "OPENAI_API_KEY",
	defaultModels: { audio: DEFAULT_MODEL },
	autoPriority: { audio: 20 },
	transcribeAudio
};
registerMediaUnderstandingProvider(openAiTranscriptionProvider);
//#endregion
export { openAiTranscriptionProvider };

//# sourceMappingURL=openai-transcription.js.map