"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeepGramSttProvider = void 0;
const logger_1 = __importDefault(require("../../logger"));
const cache_1 = require("../../cache");
const envars_1 = require("../../envars");
const shared_1 = require("../shared");
class DeepGramSttProvider {
    constructor(modelName = 'nova-3', options = {}) {
        const { id, config } = options;
        this.modelName = modelName;
        this.id = id ? () => id : this.id;
        this.config = config || { diarize: true, punctuate: true, detect_language: true, utterances: false };
    }
    id() {
        return `deepgram:stt:${this.modelName}`;
    }
    toString() {
        return `[Deepgram Provider ${this.modelName}]`;
    }
    getApiKey() {
        return (0, envars_1.getEnvString)('DEEPGRAM_API_KEY');
    }
    /**
     * Transcribe base64-encoded audio. Content-Type must match the encoded bytes (wav, mpeg, opus, …).
     */
    async transcribeBase64Audio(audioBase64, contentType = 'audio/wav') {
        let url = `https://api.deepgram.com/v1/listen?punctuate=${this.config.punctuate}&diarize=${this.config.diarize}&model=${this.modelName}&utterances=true&utt_split=1`;
        if (this.config.detect_language) {
            url += `&detect_language=true `;
        }
        else {
            url += `&language=${this.config.language || 'en'}`;
        }
        logger_1.default.debug(`Deepgram API request: ${url}`);
        let response;
        try {
            response = await (0, cache_1.fetchWithCache)(url, {
                method: 'POST',
                headers: {
                    'Content-Type': contentType,
                    Accept: 'application/json',
                    ...(this.getApiKey() ? { Authorization: `Token ${this.getApiKey()}` } : {}),
                },
                body: Buffer.from(audioBase64, 'base64'),
            }, shared_1.REQUEST_TIMEOUT_MS);
            logger_1.default.debug(`Deepgram API response: ${JSON.stringify(response.data)}`);
            if (response.data.error) {
                return {
                    error: ` Deepgram API call error: ${response.data.error}`,
                };
            }
            let transcript = '';
            if (response.data.results?.utterances?.length > 0) {
                response.data.results?.utterances.map((utterance) => {
                    transcript += (utterance.transcript || '') + '\n';
                });
            }
            else {
                transcript = response.data.results?.channels?.[0]?.alternatives?.[0]?.transcript || '';
            }
            const duration = response.data?.metadata?.duration;
            return {
                output: transcript,
                ...(typeof duration === 'number' ? { tokenUsage: { duration } } : {}),
            };
        }
        catch (err) {
            return {
                error: `API call error: ${String(err)}. Output:\n${response?.data}`,
            };
        }
    }
    async callApi(prompt) {
        return this.transcribeBase64Audio(prompt, 'audio/wav');
    }
}
exports.DeepGramSttProvider = DeepGramSttProvider;
//# sourceMappingURL=deepgram.js.map