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

export async function generateSpellingBeeHints() {
    const date = new Date().toISOString().split('T')[0];
    
    const isProduction = process.env.NODE_ENV === 'production';
    const baseDir = path.join(__dirname, '..', '..', '..');
    const hintsDir = isProduction
      ? path.join(baseDir, 'nytsolvers', 'dist', 'client', 'hints', 'spellingbee')
      : path.join(baseDir, 'project', 'public', 'hints', 'spellingbee');
    
    if (!fs.existsSync(hintsDir)) {
      fs.mkdirSync(hintsDir, { recursive: true });
    }

    try {
        const API_URL = isProduction 
          ? `https://api.nytsolvers.com/api/spellingbee/today?date=${date}` 
          : `http://localhost:5000/api/spellingbee/today?date=${date}`;

        const response = await axios.get(API_URL);
        const data = response.data;

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

        const puzzleData = {
          date: puzzleDate,
          number: data.id,
          centerLetter: data.center_letter.toUpperCase(),
          outerLetters: data.outer_letters.split('').map((l: string) => l.toUpperCase()),
          pangrams: data.pangrams,
          answers: data.answers,
        };

        fs.writeFileSync(filePath, JSON.stringify(puzzleData, null, 2), 'utf8');
        console.log(`Successfully generated Spelling Bee hints: ${filePath}`);

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

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