import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { runAudioTranscription } from "../../media-understanding/audio-transcription-runner.js";
import { resolveSTTProviderChain } from "./factory.js";
//#region src/voice/stt/transcribe-core.ts
init_logger();
const log = createLogger("STT");
function classifyFailureReason(reason) {
	if (!reason) return "unknown";
	const lower = reason.toLowerCase();
	if (lower.includes("not configured") || lower.includes("api key") || lower.includes("missing")) return "not_configured";
	if (lower.includes("timeout") || lower.includes("timed out") || lower.includes("aborted")) return "timeout";
	if (lower.includes("unsupported") || lower.includes("format")) return "unsupported_format";
	return "provider_error";
}
function toAttempt(attempt) {
	return {
		provider: attempt.provider ?? "unknown",
		outcome: attempt.outcome,
		reasonCode: attempt.outcome === "success" ? "success" : classifyFailureReason(attempt.reason),
		latencyMs: 0,
		...attempt.reason ? { error: attempt.reason } : {}
	};
}
async function transcribe(audioBuffer, config, options) {
	if (!config.enabled) throw new Error("STT is not enabled");
	const providers = resolveSTTProviderChain(config);
	if (providers.length === 0) throw new Error("No STT providers configured");
	const providersWithLanguage = options?.language ? providers.map((p) => ({
		...p,
		language: options.language
	})) : providers;
	const result = await runAudioTranscription({
		providers: providersWithLanguage,
		attachments: [{
			attachmentIndex: 0,
			buffer: audioBuffer,
			fileName: `audio-${Date.now()}.ogg`,
			mime: "audio/ogg"
		}],
		timeoutMs: config.timeoutMs ?? 6e4
	});
	const attachmentDecision = result.decision.attachments[0];
	const attempts = (attachmentDecision?.attempts ?? []).map(toAttempt);
	const attemptedProviders = attempts.map((a) => a.provider);
	if (!attachmentDecision?.chosen) {
		log.error({
			attempts,
			attemptedProviders
		}, "All STT providers failed");
		const lastError = attempts.find((a) => a.outcome === "failed")?.error;
		throw new Error(lastError ?? "All STT providers failed");
	}
	const chosen = attachmentDecision.chosen;
	const output = result.outputs[0];
	if (!output) throw new Error("STT runner returned chosen attempt but no output text");
	const primaryProvider = providersWithLanguage[0].id;
	const fallbackFrom = chosen.provider && chosen.provider !== primaryProvider ? primaryProvider : void 0;
	return {
		text: output.text,
		provider: chosen.provider ?? "unknown",
		...chosen.model ? { language: options?.language } : {},
		attempts,
		...fallbackFrom ? { fallbackFrom } : {},
		attemptedProviders
	};
}
//#endregion
export { transcribe };

//# sourceMappingURL=transcribe-core.js.map