import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();

const modelName = process.env.GEMINI_MODEL || 'gemini-2.0-flash';

export async function generateText(prompt) {
    const apiKey = process.env.GEMINI_API_KEY;
    if (!apiKey) throw new Error('GEMINI_API_KEY is not set in .env');

    const interval = parseInt(process.env.GEMINI_API_INTERVAL_MS) || 5000;
    console.log(`[generateText] Waiting ${interval}ms before API call...`);
    await new Promise(resolve => setTimeout(resolve, interval));

    const url = `https://generativelanguage.googleapis.com/v1beta/models/${modelName}:generateContent`;
    const payload = { contents: [{ parts: [{ text: prompt }] }] };

    try {
        const response = await axios.post(url, payload, {
            headers: { 'Content-Type': 'application/json', 'X-goog-api-key': apiKey },
            timeout: 60000
        });
        return response.data?.candidates?.[0]?.content?.parts?.[0]?.text || '';
    } catch (err) {
        throw err;
    }
}
