"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzureSpeechTtsProvider = void 0;
const fs_1 = __importDefault(require("fs"));
const speechSdk = __importStar(require("microsoft-cognitiveservices-speech-sdk"));
const path_1 = __importDefault(require("path"));
const uuid_1 = require("uuid");
const logger_1 = __importDefault(require("../../logger"));
class AzureSpeechTtsProvider {
    constructor(modelName = 'azure-speech', options = {}) {
        this.speechConfig = null;
        const { id, config } = options;
        this.modelName = modelName;
        this.id = id ? () => id : this.id;
        this.config = config || {
            language: 'en-US',
            voiceName: 'en-US-AndrewMultilingualNeural',
            outputFormat: 'riff-16khz-16bit-mono-pcm', // Default to WAV format
        };
        // Initialize Speech SDK config
        this.initializeSpeechConfig();
    }
    initializeSpeechConfig() {
        try {
            const apiKey = this.getApiKey();
            const region = this.getRegion();
            if (!apiKey || !region) {
                logger_1.default.warn('Azure Speech SDK credentials not configured');
                return;
            }
            this.speechConfig = speechSdk.SpeechConfig.fromSubscription(apiKey, region);
            // Set default configurations
            this.speechConfig.speechSynthesisLanguage = this.config.language || 'en-US';
            this.speechConfig.speechSynthesisVoiceName =
                this.config.voiceName || 'en-US-AndrewMultilingualNeural';
            if (this.config.outputFormat) {
                const formatMap = {
                    'audio-16khz-128kbitrate-mono-mp3': speechSdk.SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3,
                    'audio-24khz-160kbitrate-mono-mp3': speechSdk.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3,
                    'audio-48khz-192kbitrate-mono-mp3': speechSdk.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3,
                    'riff-16khz-16bit-mono-pcm': speechSdk.SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm,
                    'riff-24khz-16bit-mono-pcm': speechSdk.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm,
                    'ogg-opus-16khz-16bit-mono-opus': speechSdk.SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus,
                    'ogg-opus-24khz-16bit-mono-opus': speechSdk.SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus,
                    'ogg-opus-48khz-16bit-mono-opus': speechSdk.SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus,
                };
                const format = formatMap[this.config.outputFormat];
                if (format !== undefined) {
                    this.speechConfig.speechSynthesisOutputFormat = format;
                }
            }
            logger_1.default.debug('Azure Speech SDK initialized successfully');
        }
        catch (err) {
            logger_1.default.warn('Failed to initialize Azure Speech SDK');
            if (err instanceof Error) {
                logger_1.default.debug(err.message);
            }
        }
    }
    id() {
        return `azure-speech:tts:${this.modelName}`;
    }
    toString() {
        return `[Azure Speech TTS Provider ${this.modelName}]`;
    }
    getApiKey() {
        return process.env.SPEECH_SERVICE_KEY;
    }
    getRegion() {
        return process.env.SPEECH_SERVICE_REGION;
    }
    /**
     * Get voice name based on language and gender
     * Mapping of common languages to Azure Neural voices
     */
    getVoiceNameByLanguage(language = 'en-US', gender = 'female') {
        const voiceMap = {
            'en-US': { male: 'en-US-AndrewMultilingualNeural', female: 'en-US-AvaMultilingualNeural' },
            'en-GB': { male: 'en-GB-RyanNeural', female: 'en-GB-SoniaNeural' },
            'en-AU': { male: 'en-AU-WilliamNeural', female: 'en-AU-NatashaNeural' },
            'en-CA': { male: 'en-CA-LiamNeural', female: 'en-CA-ClaraNeural' },
            'es-ES': { male: 'es-ES-AlvaroNeural', female: 'es-ES-ElviraNeural' },
            'es-MX': { male: 'es-MX-JorgeNeural', female: 'es-MX-DaliaNeural' },
            'fr-FR': { male: 'fr-FR-HenriNeural', female: 'fr-FR-DeniseNeural' },
            'fr-CA': { male: 'fr-CA-AntoineNeural', female: 'fr-CA-SylvieNeural' },
            'de-DE': { male: 'de-DE-ConradNeural', female: 'de-DE-KatjaNeural' },
            'it-IT': { male: 'it-IT-DiegoNeural', female: 'it-IT-ElsaNeural' },
            'pt-BR': { male: 'pt-BR-AntonioNeural', female: 'pt-BR-FranciscaNeural' },
            'pt-PT': { male: 'pt-PT-DuarteNeural', female: 'pt-PT-RaquelNeural' },
            'ja-JP': { male: 'ja-JP-KeitaNeural', female: 'ja-JP-NanamiNeural' },
            'zh-CN': { male: 'zh-CN-YunxiNeural', female: 'zh-CN-XiaoxiaoNeural' },
            'ko-KR': { male: 'ko-KR-InJoonNeural', female: 'ko-KR-SunHiNeural' },
            'hi-IN': { male: 'hi-IN-MadhurNeural', female: 'hi-IN-SwaraNeural' },
            'ar-SA': { male: 'ar-SA-HamedNeural', female: 'ar-SA-ZariyahNeural' },
            'ar-AE': { male: 'ar-AE-HamdanNeural', female: 'ar-AE-FatimaNeural' },
            'ru-RU': { male: 'ru-RU-DmitryNeural', female: 'ru-RU-SvetlanaNeural' },
            'pl-PL': { male: 'pl-PL-MarekNeural', female: 'pl-PL-ZofiaNeural' },
            'nl-NL': { male: 'nl-NL-MaartenNeural', female: 'nl-NL-ColetteNeural' },
            'sv-SE': { male: 'sv-SE-MattiasNeural', female: 'sv-SE-SofieNeural' },
            'tr-TR': { male: 'tr-TR-AhmetNeural', female: 'tr-TR-EmelNeural' },
            'id-ID': { male: 'id-ID-ArdiNeural', female: 'id-ID-GadisNeural' },
            'th-TH': { male: 'th-TH-NiwatNeural', female: 'th-TH-PremwadeeNeural' },
            'vi-VN': { male: 'vi-VN-NamMinhNeural', female: 'vi-VN-HoaiMyNeural' },
        };
        const voices = voiceMap[language];
        if (voices) {
            return voices[gender];
        }
        // Default fallback
        return 'en-US-AndrewMultilingualNeural';
    }
    /**
     * Map common language values to Azure language codes
     */
    mapLanguageToAzureCode(language) {
        const languageMap = {
            american: 'en-US',
            british: 'en-GB',
            australian: 'en-AU',
            canadian: 'en-CA',
            english: 'en-US',
            spanish: 'es-ES',
            spain: 'es-ES',
            mexico: 'es-MX',
            french: 'fr-FR',
            france: 'fr-FR',
            german: 'de-DE',
            italian: 'it-IT',
            portuguese: 'pt-PT',
            brazil: 'pt-BR',
            portugal: 'pt-PT',
            japanese: 'ja-JP',
            chinese: 'zh-CN',
            korean: 'ko-KR',
            hindi: 'hi-IN',
            indian: 'hi-IN',
            arabic: 'ar-SA',
            'saudi arabia': 'ar-SA',
            uae: 'ar-AE',
            russian: 'ru-RU',
            polish: 'pl-PL',
            dutch: 'nl-NL',
            swedish: 'sv-SE',
            turkish: 'tr-TR',
            indonesian: 'id-ID',
        };
        return languageMap[language.toLowerCase()] || language;
    }
    async callApi(text) {
        if (!this.speechConfig) {
            return {
                error: 'Azure Speech SDK not initialized. Please configure SPEECH_SERVICE_KEY and SPEECH_SERVICE_REGION.',
            };
        }
        try {
            logger_1.default.debug(`Azure Speech TTS request: text length=${text.length}`);
            // Create temporary audio file
            const tempDir = path_1.default.resolve('temp_azure_audio');
            if (!fs_1.default.existsSync(tempDir)) {
                fs_1.default.mkdirSync(tempDir, { recursive: true });
            }
            const tempAudioFile = path_1.default.join(tempDir, `${(0, uuid_1.v4)()}.wav`);
            // Create audio config
            const audioConfig = speechSdk.AudioConfig.fromAudioFileOutput(tempAudioFile);
            // Create synthesizer
            const synthesizer = new speechSdk.SpeechSynthesizer(this.speechConfig, audioConfig);
            // Synthesize speech
            const result = await new Promise((resolve, reject) => {
                synthesizer.speakTextAsync(text, (result) => {
                    if (result.reason === speechSdk.ResultReason.SynthesizingAudioCompleted) {
                        synthesizer.close();
                        // Read the generated audio file
                        try {
                            const audioBuffer = fs_1.default.readFileSync(tempAudioFile);
                            // Clean up temp file
                            if (fs_1.default.existsSync(tempAudioFile)) {
                                fs_1.default.unlinkSync(tempAudioFile);
                            }
                            resolve(audioBuffer);
                        }
                        catch (err) {
                            reject(err);
                        }
                    }
                    else {
                        synthesizer.close();
                        reject(new Error(`Speech synthesis failed: ${result.errorDetails}`));
                    }
                }, (error) => {
                    synthesizer.close();
                    // Clean up temp file on error
                    if (fs_1.default.existsSync(tempAudioFile)) {
                        fs_1.default.unlinkSync(tempAudioFile);
                    }
                    reject(error);
                });
            });
            logger_1.default.debug(`Azure Speech TTS response: Generated audio buffer of size ${result.length} bytes`);
            // Determine format from outputFormat config, default to 'wav' if not defined
            let audioFormat = 'wav'; // Default to wav
            if (this.config.outputFormat) {
                if (this.config.outputFormat.includes('mp3')) {
                    audioFormat = 'mp3';
                }
                else if (this.config.outputFormat.includes('ogg-opus') || this.config.outputFormat.includes('opus')) {
                    audioFormat = 'opus';
                }
                else if (this.config.outputFormat.includes('pcm') || this.config.outputFormat.includes('riff')) {
                    audioFormat = 'wav';
                }
            }
            // Return audio as base64 string with format information
            return {
                output: result.toString('base64'),
                audio: {
                    data: result.toString('base64'),
                    format: audioFormat,
                },
            };
        }
        catch (err) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            logger_1.default.error(`Azure Speech API call error: ${errorMessage}`);
            return {
                error: `Azure Speech API call error: ${errorMessage}`,
            };
        }
    }
    /**
     * Convert text to speech and return as Buffer
     * This is a convenience method that wraps callApi
     */
    async textToSpeechBuffer(text) {
        const response = await this.callApi(text);
        if (response.error) {
            logger_1.default.error(`Failed to convert text to speech: ${response.error}`);
            return null;
        }
        if (!response.output || typeof response.output !== 'string') {
            logger_1.default.error('Invalid response from Azure Speech API');
            return null;
        }
        return Buffer.from(response.output, 'base64');
    }
    /**
     * Generate voice file and return file path
     * @param text - Text to convert to speech
     * @param columnName - Column name for file naming
     * @param resultCounter - Counter for unique file naming
     * @param audioFolder - Folder to save audio files
     * @returns File path of generated audio
     */
    async generateVoiceFile(text, columnName, resultCounter, audioFolder) {
        if (!this.speechConfig) {
            throw new Error('Azure Speech SDK not initialized');
        }
        return new Promise((resolve, reject) => {
            const audioFileName = `${audioFolder}/${resultCounter}-${columnName}.wav`;
            const audioConfig = speechSdk.AudioConfig.fromAudioFileOutput(audioFileName);
            const synthesizer = new speechSdk.SpeechSynthesizer(this.speechConfig, audioConfig);
            synthesizer.speakTextAsync(text, (output) => {
                if (output.reason !== speechSdk.ResultReason.SynthesizingAudioCompleted) {
                    logger_1.default.error(`Speech synthesis canceled: ${JSON.stringify(output)}`);
                    synthesizer.close();
                    reject(new Error('Speech synthesis failed'));
                    return;
                }
                synthesizer.close();
                resolve(audioFileName);
            }, (err) => {
                logger_1.default.error(`Speech synthesis error: ${err}`);
                synthesizer.close();
                reject(err);
            });
        });
    }
    /**
     * Update configuration for language and voice
     */
    updateConfig(options) {
        if (!this.speechConfig) {
            logger_1.default.warn('Speech config not initialized');
            return;
        }
        if (options.language) {
            const azureLanguageCode = this.mapLanguageToAzureCode(options.language);
            this.speechConfig.speechSynthesisLanguage = azureLanguageCode;
            this.config.language = azureLanguageCode;
            // Auto-select voice if not explicitly provided
            if (!options.voiceName && options.gender) {
                const voiceName = this.getVoiceNameByLanguage(azureLanguageCode, options.gender);
                this.speechConfig.speechSynthesisVoiceName = voiceName;
                this.config.voiceName = voiceName;
                logger_1.default.info(`Auto-selected voice: ${voiceName} for language: ${azureLanguageCode}`);
            }
        }
        if (options.voiceName) {
            this.speechConfig.speechSynthesisVoiceName = options.voiceName;
            this.config.voiceName = options.voiceName;
        }
    }
}
exports.AzureSpeechTtsProvider = AzureSpeechTtsProvider;
//# sourceMappingURL=azureSpeech.js.map