"use strict";
// This file was auto-generated by Fern from our API Definition.
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechToTextClient = void 0;
const BaseClient_1 = require("../../../../BaseClient");
const core = __importStar(require("../../../../core"));
const headers_1 = require("../../../../core/headers");
const json_1 = require("../../../../core/json");
const environments = __importStar(require("../../../../environments"));
const handleNonStatusCodeError_1 = require("../../../../errors/handleNonStatusCodeError");
const errors = __importStar(require("../../../../errors/index"));
const serializers = __importStar(require("../../../../serialization/index"));
const ElevenLabs = __importStar(require("../../../index"));
const Client_1 = require("../resources/transcripts/client/Client");
class SpeechToTextClient {
    constructor(options = {}) {
        this._options = (0, BaseClient_1.normalizeClientOptions)(options);
    }
    get transcripts() {
        var _a;
        return ((_a = this._transcripts) !== null && _a !== void 0 ? _a : (this._transcripts = new Client_1.TranscriptsClient(this._options)));
    }
    /**
     * Transcribe an audio or video file. If webhook is set to true, the request will be processed asynchronously and results sent to configured webhooks. When use_multi_channel is true and the provided audio has multiple channels, a 'transcripts' object with separate transcripts for each channel is returned. Otherwise, returns a single transcript. The optional webhook_metadata parameter allows you to attach custom data that will be included in webhook responses for request correlation and tracking.
     *
     * @param {ElevenLabs.BodySpeechToTextV1SpeechToTextPost} request
     * @param {SpeechToTextClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link ElevenLabs.UnprocessableEntityError}
     *
     * @example
     *     import { createReadStream } from "fs";
     *     await client.speechToText.convert({
     *         enableLogging: true,
     *         modelId: "scribe_v2"
     *     })
     */
    convert(request, requestOptions) {
        return core.HttpResponsePromise.fromPromise(this.__convert(request, requestOptions));
    }
    __convert(request, requestOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
            const _queryParams = {};
            if (request.enableLogging != null) {
                _queryParams.enable_logging = request.enableLogging.toString();
            }
            const _request = yield core.newFormData();
            _request.append("model_id", serializers.SpeechToTextConvertRequestModelId.jsonOrThrow(request.modelId, {
                unrecognizedObjectKeys: "strip",
            }));
            if (request.file != null) {
                yield _request.appendFile("file", request.file);
            }
            if (request.languageCode != null) {
                _request.append("language_code", request.languageCode);
            }
            if (request.tagAudioEvents != null) {
                _request.append("tag_audio_events", request.tagAudioEvents.toString());
            }
            if (request.numSpeakers != null) {
                _request.append("num_speakers", request.numSpeakers.toString());
            }
            if (request.timestampsGranularity != null) {
                _request.append("timestamps_granularity", serializers.SpeechToTextConvertRequestTimestampsGranularity.jsonOrThrow(request.timestampsGranularity, {
                    unrecognizedObjectKeys: "strip",
                }));
            }
            if (request.diarize != null) {
                _request.append("diarize", request.diarize.toString());
            }
            if (request.diarizationThreshold != null) {
                _request.append("diarization_threshold", request.diarizationThreshold.toString());
            }
            if (request.additionalFormats != null) {
                _request.append("additional_formats", (0, json_1.toJson)(request.additionalFormats));
            }
            if (request.fileFormat != null) {
                _request.append("file_format", serializers.SpeechToTextConvertRequestFileFormat.jsonOrThrow(request.fileFormat, {
                    unrecognizedObjectKeys: "strip",
                }));
            }
            if (request.cloudStorageUrl != null) {
                _request.append("cloud_storage_url", request.cloudStorageUrl);
            }
            if (request.sourceUrl != null) {
                _request.append("source_url", request.sourceUrl);
            }
            if (request.webhook != null) {
                _request.append("webhook", request.webhook.toString());
            }
            if (request.webhookId != null) {
                _request.append("webhook_id", request.webhookId);
            }
            if (request.temperature != null) {
                _request.append("temperature", request.temperature.toString());
            }
            if (request.seed != null) {
                _request.append("seed", request.seed.toString());
            }
            if (request.useMultiChannel != null) {
                _request.append("use_multi_channel", request.useMultiChannel.toString());
            }
            if (request.webhookMetadata != null) {
                _request.append("webhook_metadata", (() => {
                    const mapped = serializers.SpeechToTextConvertRequestWebhookMetadata.jsonOrThrow(request.webhookMetadata, { unrecognizedObjectKeys: "strip" });
                    return typeof mapped === "string" ? mapped : (0, json_1.toJson)(mapped);
                })());
            }
            if (request.entityDetection != null) {
                if (Array.isArray(request.entityDetection))
                    for (const _item of request.entityDetection) {
                        _request.append("entity_detection", typeof _item === "string" ? _item : (0, json_1.toJson)(_item));
                    }
            }
            if (request.noVerbatim != null) {
                _request.append("no_verbatim", request.noVerbatim.toString());
            }
            if (request.entityRedaction != null) {
                if (Array.isArray(request.entityRedaction))
                    for (const _item of request.entityRedaction) {
                        _request.append("entity_redaction", typeof _item === "string" ? _item : (0, json_1.toJson)(_item));
                    }
            }
            if (request.entityRedactionMode != null) {
                _request.append("entity_redaction_mode", request.entityRedactionMode);
            }
            if (request.keyterms != null) {
                for (const _item of request.keyterms) {
                    _request.append("keyterms", _item);
                }
            }
            const _maybeEncodedRequest = yield _request.getRequest();
            const _headers = (0, headers_1.mergeHeaders)((_a = this._options) === null || _a === void 0 ? void 0 : _a.headers, (0, headers_1.mergeOnlyDefinedHeaders)(Object.assign({ "xi-api-key": (_b = requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiKey) !== null && _b !== void 0 ? _b : (_c = this._options) === null || _c === void 0 ? void 0 : _c.apiKey }, _maybeEncodedRequest.headers)), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.headers);
            const _response = yield ((_d = this._options.fetcher) !== null && _d !== void 0 ? _d : core.fetcher)({
                url: core.url.join((_f = (_e = (yield core.Supplier.get(this._options.baseUrl))) !== null && _e !== void 0 ? _e : (yield core.Supplier.get(this._options.environment))) !== null && _f !== void 0 ? _f : environments.ElevenLabsEnvironment.Production, "v1/speech-to-text"),
                method: "POST",
                headers: _headers,
                queryParameters: Object.assign(Object.assign({}, _queryParams), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.queryParams),
                requestType: "file",
                duplex: _maybeEncodedRequest.duplex,
                body: _maybeEncodedRequest.body,
                timeoutMs: ((_j = (_g = requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) !== null && _g !== void 0 ? _g : (_h = this._options) === null || _h === void 0 ? void 0 : _h.timeoutInSeconds) !== null && _j !== void 0 ? _j : 240) * 1000,
                maxRetries: (_k = requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries) !== null && _k !== void 0 ? _k : (_l = this._options) === null || _l === void 0 ? void 0 : _l.maxRetries,
                abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
                fetchFn: (_m = this._options) === null || _m === void 0 ? void 0 : _m.fetch,
                logging: this._options.logging,
            });
            if (_response.ok) {
                return {
                    data: serializers.SpeechToTextConvertResponse.parseOrThrow(_response.body, {
                        unrecognizedObjectKeys: "passthrough",
                        allowUnrecognizedUnionMembers: true,
                        allowUnrecognizedEnumValues: true,
                        breadcrumbsPrefix: ["response"],
                    }),
                    rawResponse: _response.rawResponse,
                };
            }
            if (_response.error.reason === "status-code") {
                switch (_response.error.statusCode) {
                    case 422:
                        throw new ElevenLabs.UnprocessableEntityError(_response.error.body, _response.rawResponse);
                    default:
                        throw new errors.ElevenLabsError({
                            statusCode: _response.error.statusCode,
                            body: _response.error.body,
                            rawResponse: _response.rawResponse,
                        });
                }
            }
            return (0, handleNonStatusCodeError_1.handleNonStatusCodeError)(_response.error, _response.rawResponse, "POST", "/v1/speech-to-text");
        });
    }
}
exports.SpeechToTextClient = SpeechToTextClient;
