"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transcribeDatasetAudioFile = transcribeDatasetAudioFile;
exports.transcribeDatasetAudioFromUrl = transcribeDatasetAudioFromUrl;
const fs_1 = __importDefault(require("fs"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const uuid_1 = require("uuid");
const combinedAudio_1 = require("../../../assertions/audio/combinedAudio");
const constants_1 = require("../../../constants");
const envars_1 = require("../../../envars");
const logger_1 = __importDefault(require("../../../logger"));
const datasetMediaUrlResolver_1 = require("./datasetMediaUrlResolver");
const mediaValueUtils_1 = require("./mediaValueUtils");
/**
 * Transcribe a local audio file for dataset voice rows (STT via getAudioTranscript / Deepgram).
 * Returns empty string if DEEPGRAM_API_KEY is unset or transcription fails.
 */
async function transcribeDatasetAudioFile(filePath, workspaceId) {
    if (!(0, envars_1.getEnvString)('DEEPGRAM_API_KEY')) {
        logger_1.default.debug('DEEPGRAM_API_KEY not set; skipping dataset voice transcript');
        return '';
    }
    let buf;
    try {
        buf = fs_1.default.readFileSync(filePath);
    }
    catch (e) {
        const errMsg = e instanceof Error ? e.message : String(e);
        logger_1.default.warn(`Failed to read audio for transcript: ${filePath}: ${errMsg}`);
        return '';
    }
    const ext = path_1.default.extname(filePath);
    const format = ext.replace(/^\./, '').toLowerCase() || 'wav';
    const outputAudio = {
        data: buf.toString('base64'),
        format,
    };
    try {
        const { transcript } = await (0, combinedAudio_1.getAudioTranscript)(outputAudio, '', workspaceId || undefined);
        return (transcript || '').trim();
    }
    catch (e) {
        const errMsg = e instanceof Error ? e.message : String(e);
        logger_1.default.warn(`getAudioTranscript failed for dataset file ${filePath}: ${errMsg}`);
        return '';
    }
}
function extensionForTempAudioFile(urlStr, contentType) {
    const ct = (contentType || '').split(';')[0].trim().toLowerCase();
    const fromMime = {
        'audio/mpeg': '.mp3',
        'audio/mp3': '.mp3',
        'audio/wav': '.wav',
        'audio/x-wav': '.wav',
        'audio/wave': '.wav',
        'audio/mp4': '.m4a',
        'audio/x-m4a': '.m4a',
        'audio/ogg': '.ogg',
        'audio/opus': '.opus',
        'audio/webm': '.webm',
    };
    if (fromMime[ct]) {
        return fromMime[ct];
    }
    try {
        const ext = path_1.default.extname(new URL(urlStr).pathname).toLowerCase();
        if (ext && /^\.(mp3|wav|m4a|ogg|opus|webm)$/.test(ext)) {
            return ext;
        }
    }
    catch {
        /* ignore */
    }
    return '.mp3';
}
/**
 * Download audio from an http(s) URL (including Trusys blob / SAS), transcribe, return transcript text.
 * Private Trusys blob URLs without `sig` require `token` so the server can resolve a SAS URL via Control Plane.
 */
async function transcribeDatasetAudioFromUrl(url, workspaceId, token) {
    const trimmed = url.trim();
    if (!/^https?:\/\//i.test(trimmed)) {
        return '';
    }
    let fetchUrl = trimmed;
    if ((0, datasetMediaUrlResolver_1.isTrusysAzureBlobStorageUrl)(trimmed)) {
        if (!(0, mediaValueUtils_1.urlAlreadyHasAzureSasSignature)(trimmed) && !token) {
            logger_1.default.warn('transcribeDatasetAudioFromUrl: private Trusys blob URL has no SAS and no token; cannot download for transcript');
            return '';
        }
        try {
            fetchUrl = await (0, mediaValueUtils_1.resolveMediaUrlWithSas)({
                blobUrl: trimmed,
                token,
                expiryInHours: 1,
            });
        }
        catch (e) {
            const errMsg = e instanceof Error ? e.message : String(e);
            logger_1.default.warn(`transcribeDatasetAudioFromUrl: resolveMediaUrlWithSas failed: ${errMsg}`);
            return '';
        }
    }
    let response;
    try {
        response = await fetch(fetchUrl);
    }
    catch (e) {
        const errMsg = e instanceof Error ? e.message : String(e);
        logger_1.default.warn(`transcribeDatasetAudioFromUrl fetch failed: ${errMsg}`);
        return '';
    }
    if (!response.ok) {
        logger_1.default.warn(`transcribeDatasetAudioFromUrl: HTTP ${response.status} for url`);
        return '';
    }
    const maxBytes = (0, constants_1.getDatasetAudioMaxFileBytes)();
    const arrayBuffer = await response.arrayBuffer();
    const buf = Buffer.from(arrayBuffer);
    if (buf.length > maxBytes) {
        logger_1.default.warn(`transcribeDatasetAudioFromUrl: audio exceeds max bytes (${buf.length})`);
        return '';
    }
    const ext = extensionForTempAudioFile(trimmed, response.headers.get('content-type'));
    const tmpDir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'dataset-voice-tr-'));
    const tmpFile = path_1.default.join(tmpDir, `${(0, uuid_1.v4)()}${ext}`);
    try {
        fs_1.default.writeFileSync(tmpFile, buf);
        return await transcribeDatasetAudioFile(tmpFile, workspaceId);
    }
    finally {
        try {
            fs_1.default.rmSync(tmpDir, { recursive: true, force: true });
        }
        catch {
            /* ignore */
        }
    }
}
//# sourceMappingURL=datasetVoiceTranscript.js.map