import { GoogleGenerativeAI } from "@google/generative-ai";

const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
// Fail open without throwing at module import time; initialize lazily
const genAI = GEMINI_API_KEY ? new GoogleGenerativeAI(GEMINI_API_KEY) : null;

export async function isSpamWithGemini(message: string): Promise<boolean> {
  try {
    if (!genAI) {
      console.warn('[Gemini] API key not set; skipping spam check.');
      return false;
    }
    const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
    const prompt = `Is the following message spam? Reply with only 'yes' or 'no'.\n\nMessage:\n${message}`;
    const result = await model.generateContent(prompt);
    const response = result.response.text().trim().toLowerCase();
    // Do not log PII or model responses in production
    return response.startsWith("yes");
  } catch (err: any) {
    if (err?.response?.status === 401) {
      console.error('[Gemini] API key expired or invalid.');
    } else if (err?.code === 'ENOTFOUND' || err?.code === 'ECONNREFUSED') {
      console.error('[Gemini] Service not reachable:', err.message);
    } else {
      console.error('[Gemini] Error during spam check:', err);
    }
    // Fail open: if Gemini is not reachable, do not block the message as spam
    return false;
  }
} 