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

const getClient = () => {
  const apiKey = process.env.API_KEY;
  if (!apiKey) {
    console.error("API Key is missing. Magic text will fail.");
  }
  return new GoogleGenAI({ apiKey: apiKey || 'dummy-key-prevent-crash' });
};

export const generateBusinessContent = async (businessName: string, businessType: string) => {
  try {
    const ai = getClient();
    const model = "gemini-2.5-flash";
    
    const prompt = `
    Create website content for a small business.
    Business Name: ${businessName}
    Business Type: ${businessType}
    
    I need:
    1. A Catchy Title
    2. An "About Us" paragraph (approx 40 words) for the hero section.
    3. A secondary paragraph about services/values (approx 40 words) for the first section.
    4. A third paragraph describing expertise or team (approx 40 words) for the second section.
    5. A short Call to Action button text (max 3 words).
    `;

    const response = await ai.models.generateContent({
      model: model,
      contents: prompt,
      config: {
        responseMimeType: "application/json",
        responseSchema: {
            type: Type.OBJECT,
            properties: {
                title: { type: Type.STRING },
                description: { type: Type.STRING },
                secondParagraph: { type: Type.STRING },
                thirdParagraph: { type: Type.STRING },
                ctaText: { type: Type.STRING }
            },
            required: ["title", "description", "secondParagraph", "thirdParagraph", "ctaText"]
        }
      }
    });

    if (response.text) {
        return JSON.parse(response.text);
    }
    throw new Error("No text generated");

  } catch (error) {
    console.error("Gemini Generation Error:", error);
    return {
        title: `Welcome to ${businessName}`,
        description: `We are a leading ${businessType} dedicated to serving our customers with quality and integrity.`,
        secondParagraph: "Explore our services and find out why our customers trust us to deliver the best results every time.",
        thirdParagraph: "Our team brings years of experience and passion to every project, ensuring your complete satisfaction.",
        ctaText: "Contact Us"
    };
  }
};

export const generateImage = async (prompt: string) => {
  try {
    const ai = getClient();
    // Using gemini-2.5-flash-image for standard image generation tasks
    const response = await ai.models.generateContent({
      model: 'gemini-2.5-flash-image',
      contents: {
        parts: [{ text: prompt }]
      },
      config: {
        // These are not supported for nano banana series models (flash-image)
        responseMimeType: undefined,
        responseSchema: undefined
      }
    });

    if (response.candidates?.[0]?.content?.parts) {
        for (const part of response.candidates[0].content.parts) {
            if (part.inlineData) {
                return `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`;
            }
        }
    }
    throw new Error("No image data found in response");
  } catch (error) {
    console.error("Gemini Image Gen Error:", error);
    throw error;
  }
};