import { GraphAILogger } from "graphai";
import { AuthenticationError, RateLimitError } from "openai";
import { provider2TTSAgent } from "../types/provider2agent.js";
import { createOpenAIClient } from "../utils/openai_client.js";
import { apiKeyMissingError, agentIncorrectAPIKeyError, agentAPIRateLimitError, agentGenerationError, audioAction, audioFileTarget, } from "../utils/error_cause.js";
export const ttsOpenaiAgent = async ({ namedInputs, params, config, }) => {
    const { text } = namedInputs;
    const { model, voice, suppressError, instructions, speed } = params;
    const { apiKey, baseURL, apiVersion } = config ?? {};
    if (!apiKey) {
        throw new Error("OpenAI API key is required (OPENAI_API_KEY)", {
            cause: apiKeyMissingError("ttsOpenaiAgent", audioAction, "OPENAI_API_KEY"),
        });
    }
    const openai = createOpenAIClient({ apiKey, baseURL, apiVersion });
    try {
        const tts_options = {
            model: model ?? provider2TTSAgent.openai.defaultModel,
            voice: voice ?? provider2TTSAgent.openai.defaultVoice,
            input: text,
        };
        if (instructions) {
            tts_options["instructions"] = instructions;
        }
        if (speed) {
            tts_options["speed"] = speed;
        }
        GraphAILogger.log("ttsOptions", tts_options);
        const response = await openai.audio.speech.create(tts_options);
        const buffer = Buffer.from(await response.arrayBuffer());
        return { buffer };
    }
    catch (error) {
        if (suppressError) {
            return {
                error,
            };
        }
        GraphAILogger.error(error);
        if (error instanceof AuthenticationError) {
            throw new Error("Failed to generate audio: 401 Incorrect API key provided with OpenAI", {
                cause: agentIncorrectAPIKeyError("ttsOpenaiAgent", audioAction, audioFileTarget),
            });
        }
        if (error instanceof RateLimitError) {
            throw new Error("You exceeded your current quota", {
                cause: agentAPIRateLimitError("ttsOpenaiAgent", audioAction, audioFileTarget),
            });
        }
        if (error && typeof error === "object" && "error" in error) {
            GraphAILogger.info("tts_openai_agent: ");
            GraphAILogger.info(error.error);
            throw new Error("TTS OpenAI Error: " + JSON.stringify(error.error, null, 2), {
                cause: agentGenerationError("ttsOpenaiAgent", audioAction, audioFileTarget),
            });
        }
        else if (error instanceof Error) {
            GraphAILogger.info("tts_openai_agent: ");
            GraphAILogger.info(error.message);
            throw new Error("TTS OpenAI Error: " + error.message, {
                cause: agentGenerationError("ttsOpenaiAgent", audioAction, audioFileTarget),
            });
        }
    }
};
const ttsOpenaiAgentInfo = {
    name: "ttsOpenaiAgent",
    agent: ttsOpenaiAgent,
    mock: ttsOpenaiAgent,
    samples: [],
    description: "OpenAI TTS agent",
    category: ["tts"],
    author: "Receptron Team",
    repository: "https://github.com/receptron/mulmocast-cli/",
    license: "MIT",
    environmentVariables: ["OPENAI_API_KEY"],
};
export default ttsOpenaiAgentInfo;
