import axios from 'axios';
import fs from 'fs';
import path from 'path';
import { pingDailyPuzzleUpdated } from '../services/indexingService';

const apiKey = process.env.GEMINI_API_KEY;

  

export async function generateConnectionsHints() {
    const date = new Date().toISOString().split('T')[0];
      if (!apiKey) {
        console.error("GEMINI_API_KEY is not defined in environment variables.");
        return;
    }
    const isProduction = process.env.NODE_ENV === 'production';
    const baseDir = path.join(__dirname, '..', '..', '..');
    const hintsDir = isProduction
      ? path.join(baseDir, 'nytsolvers', 'dist', 'client', 'hints', 'connections')
      : path.join(baseDir, 'project', 'public', 'hints', 'connections');
    
    if (!fs.existsSync(hintsDir)) {
      fs.mkdirSync(hintsDir, { recursive: true });
    }

    const filePath = path.join(hintsDir, `${date}.json`);

    try {
        const url = `https://www.nytimes.com/svc/connections/v2/${date}.json`;
        const nytResponse = await axios.get(url, { headers: { 'User-Agent': 'Mozilla/5.0' } });
        const nytData = nytResponse.data;

        if (!nytData.categories) {
            console.error('Invalid NYT response');
            return;
        }

        // Generate AI hints for each category
        for (const category of nytData.categories) {
            const words = category.cards.map((card: any) => card.content);
            const theme = words.join(', ');
            const prompt = `You are a puzzle solver who specializes in identifying word connections from the NYT 'Connections' puzzle. When I give you the theme for today’s puzzle, your job is to provide a concise hint that helps understand what the theme represents — not the full answer. Make sure the theme is easier to understand and no specific audience is mentioned. The hint should sound like a brief clue or definition. The theme is: ${theme}.`;

            const data = {
                contents: [
                    {
                        parts: [
                            {
                                text: prompt
                            }
                        ]
                    }
                ]
            };

            try {
                const geminiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
                const geminiResponse = await axios.post(geminiUrl, data, {
                    headers: { 'Content-Type': 'application/json' },
                    timeout: 10000
                });

                let hint =
                    geminiResponse.data?.candidates?.[0]?.content?.parts?.[0]?.text ||
                    "Hint unavailable";

                hint = hint
                    .trim()
                    .replace(/^Your hint is\s*/i, '')
                    .replace(/[\*"]+/g, '')
                    .replace(/[.,!?]+$/, '');

                category.ai_hint = hint;
            } catch (err: any) {
                console.error("Error generating hint:", err.response?.data || err.message);
                category.ai_hint = "Hint unavailable";
            }
        }

        // ✅ Save to file
        fs.writeFileSync(filePath, JSON.stringify(nytData, null, 2), 'utf8');
        console.log(`Successfully generated Connections hints: ${filePath}`);

        // Trigger search engine indexing (Google Indexing API & Bing IndexNow)
        await pingDailyPuzzleUpdated('connections-hints', date).catch((err: any) =>
          console.error('[Connections] Error pinging search indexing:', err.message)
        );

    } catch (error) {
        console.error("Error in generateConnectionsHints:", error);
    }
};
