/**
 * src/models/gemini.ts
 * مزود Gemini 2.5 Flash عبر Google AI — للتصنيف السريع والمهام البسيطة
 * Uses native Gemini REST API (not OpenAI-compatible)
 */
import { config, MODELS } from '../config.js';
import { createChildLogger } from '../utils/logger.js';
import { ModelError, } from './provider.js';
const log = createChildLogger('models:gemini');
const GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta';
// ─── Provider ────────────────────────────────────────────────────────
export class GeminiProvider {
    name = 'gemini';
    model = MODELS.router.model;
    async chat(messages, options = {}) {
        const startTime = Date.now();
        // تحويل الرسائل من صيغة OpenAI إلى صيغة Gemini
        const { systemInstruction, contents } = convertMessages(messages);
        const body = { contents };
        if (systemInstruction) {
            body.systemInstruction = { parts: [{ text: systemInstruction }] };
        }
        body.generationConfig = {
            temperature: options.temperature ?? 0.2,
            maxOutputTokens: options.maxTokens ?? 1024,
        };
        if (options.topP !== undefined)
            body.generationConfig.topP = options.topP;
        if (options.stop)
            body.generationConfig.stopSequences = options.stop;
        if (options.responseFormat?.type === 'json_object') {
            body.generationConfig.responseMimeType = 'application/json';
        }
        const url = `${GEMINI_BASE_URL}/models/${this.model}:generateContent?key=${config.GOOGLE_AI_API_KEY}`;
        log.debug({ model: this.model, messageCount: messages.length }, 'Calling Gemini API');
        const response = await fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
            signal: AbortSignal.timeout(60_000),
        });
        if (!response.ok) {
            const errorText = await response.text().catch(() => 'Unknown error');
            const latencyMs = Date.now() - startTime;
            log.error({ model: this.model, status: response.status, errorText, latencyMs }, 'Gemini API failed');
            throw new ModelError(`Gemini API error: ${response.status} — ${errorText}`, response.status, this.model);
        }
        const data = (await response.json());
        const latencyMs = Date.now() - startTime;
        const candidate = data.candidates?.[0];
        if (!candidate) {
            throw new ModelError('Gemini returned no candidates', 500, this.model);
        }
        const content = candidate.content.parts.map(p => p.text).join('');
        const result = {
            content,
            tokensInput: data.usageMetadata?.promptTokenCount ?? 0,
            tokensOutput: data.usageMetadata?.candidatesTokenCount ?? 0,
            model: data.modelVersion || this.model,
            latencyMs,
            finishReason: candidate.finishReason,
        };
        log.debug({ model: this.model, tokensIn: result.tokensInput, tokensOut: result.tokensOutput, latencyMs }, 'Gemini call completed');
        return result;
    }
}
// ─── Message Conversion ──────────────────────────────────────────────
/** تحويل رسائل OpenAI إلى صيغة Gemini */
function convertMessages(messages) {
    let systemInstruction = null;
    const contents = [];
    for (const msg of messages) {
        if (msg.role === 'system') {
            // Gemini uses systemInstruction separately
            systemInstruction = systemInstruction
                ? `${systemInstruction}\n\n${msg.content}`
                : msg.content;
        }
        else {
            const role = msg.role === 'assistant' ? 'model' : 'user';
            // Gemini needs alternating roles — merge consecutive same-role messages
            const last = contents[contents.length - 1];
            if (last && last.role === role) {
                last.parts.push({ text: msg.content });
            }
            else {
                contents.push({ role, parts: [{ text: msg.content }] });
            }
        }
    }
    return { systemInstruction, contents };
}
// Singleton
export const gemini = new GeminiProvider();
//# sourceMappingURL=gemini.js.map