import { GoogleGenerativeAI } from '@google/generative-ai';
import { reportMetric } from '../metrics-reporter.js';

const MODELS = {
  flash: 'gemini-3-flash-preview',
  lite: 'gemini-3.1-flash-lite-preview',
} as const;

export type GeminiModel = keyof typeof MODELS;

let _client: GoogleGenerativeAI | null = null;

function getClient(apiKey: string): GoogleGenerativeAI {
  if (!_client) _client = new GoogleGenerativeAI(apiKey);
  return _client;
}

export async function transcribeAudio(
  audioBase64: string,
  mimeType: string,
  apiKey: string,
): Promise<string> {
  const client = getClient(apiKey);
  const genModel = client.getGenerativeModel({ model: MODELS.flash });
  const result = await genModel.generateContent([
    { inlineData: { mimeType, data: audioBase64 } },
    {
      text: 'Transcribe this voice message accurately. Return only the transcribed text, nothing else. If the message is in Hebrew, transcribe in Hebrew.',
    },
  ]);
  const usage = result.response.usageMetadata;
  void reportMetric({
    model: MODELS.flash,
    tokens_in: usage?.promptTokenCount ?? 0,
    tokens_out: usage?.candidatesTokenCount ?? 0,
    call_type: 'voice',
  });
  return result.response.text().trim();
}

export async function generateText(
  prompt: string,
  apiKey: string,
  model: GeminiModel = 'flash',
): Promise<string> {
  const client = getClient(apiKey);
  try {
    const genModel = client.getGenerativeModel({ model: MODELS[model] });
    const result = await genModel.generateContent(prompt);
    return result.response.text();
  } catch (err) {
    // Fallback to lite if flash fails
    if (model === 'flash') {
      const liteModel = client.getGenerativeModel({ model: MODELS.lite });
      const result = await liteModel.generateContent(prompt);
      return result.response.text();
    }
    throw err;
  }
}
