import { GoogleGenAI } from "@google/genai";

const apiKey = process.env.API_KEY || ''; 

// Safe initialization
let ai: GoogleGenAI | null = null;
if (apiKey) {
  ai = new GoogleGenAI({ apiKey });
}

export const GeminiService = {
  isEnabled: !!apiKey,

  /**
   * Generates a technical description and tags for a code snippet.
   */
  analyzeCode: async (code: string): Promise<{ description: string; tags: string[] }> => {
    if (!ai) return { description: "AI Unavailable (Missing Key)", tags: [] };

    try {
      const response = await ai.models.generateContent({
        model: 'gemini-2.5-flash',
        contents: `Analyze this code snippet. Return a JSON object with a 'description' (max 50 words, technical style) and 'tags' (array of strings, max 5). Code: \n\n${code}`,
        config: {
          responseMimeType: 'application/json'
        }
      });
      
      const text = response.text;
      if (!text) return { description: "Analysis failed", tags: [] };
      
      const result = JSON.parse(text);
      return {
        description: result.description || "No description generated.",
        tags: result.tags || []
      };
    } catch (error) {
      console.error("Gemini Error:", error);
      return { description: "Error during AI analysis.", tags: [] };
    }
  },

  /**
   * Generates a constructive code review or explanation.
   */
  explainCode: async (code: string): Promise<string> => {
    if (!ai) return "AI Configuration Missing.";

    try {
      const response = await ai.models.generateContent({
        model: 'gemini-2.5-flash',
        contents: `Explain this code snippet like a senior engineer doing a code review. Be concise, point out optimizations if any. Code: \n${code}`,
      });
      return response.text || "No explanation available.";
    } catch (e) {
      return "Failed to generate explanation.";
    }
  }
};
