import { handleGeminiError } from "./Errors.js";
import { BinaryUtils } from "../../utils/Binary.js";
import { logger } from "../../utils/logger.js";
export class GeminiTranscription {
    baseUrl;
    apiKey;
    static DEFAULT_PROMPT = "Transcribe the provided audio and respond with only the transcript text.";
    constructor(baseUrl, apiKey) {
        this.baseUrl = baseUrl;
        this.apiKey = apiKey;
    }
    async execute(request) {
        const model = request.model || "gemini-2.0-flash";
        const url = `${this.baseUrl}/models/${model}:generateContent?key=${this.apiKey}`;
        const result = await BinaryUtils.toBase64(request.file);
        if (!result) {
            throw new Error(`Failed to load audio file: ${request.file}`);
        }
        const { data: base64Data, mimeType } = result;
        let prompt = GeminiTranscription.DEFAULT_PROMPT;
        if (request.language) {
            prompt += ` Respond in the ${request.language} language.`;
        }
        if (request.prompt) {
            prompt += ` ${request.prompt}`;
        }
        const payload = {
            contents: [
                {
                    role: "user",
                    parts: [
                        { text: prompt },
                        {
                            inlineData: {
                                mimeType,
                                data: base64Data
                            }
                        }
                    ]
                }
            ],
            generationConfig: {
                responseMimeType: "text/plain"
            }
        };
        logger.logRequest("Gemini", "POST", url, payload);
        const response = await fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        });
        if (!response.ok) {
            await handleGeminiError(response, model);
        }
        const json = (await response.json());
        logger.logResponse("Gemini", response.status, response.statusText, json);
        const text = json.candidates?.[0]?.content?.parts?.map((p) => p.text).join("") || "";
        return {
            text,
            model,
            segments: [] // Gemini's generateContent doesn't return segments by default
        };
    }
}
