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

export async function generateMiniCrosswordHints() {
    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', 'minicrossword')
      : path.join(baseDir, 'project', 'public', 'hints', 'minicrossword');
    
    if (!fs.existsSync(hintsDir)) {
      fs.mkdirSync(hintsDir, { recursive: true });
    }

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

    try {
        const API_URL = isProduction
          ? 'https://api.nytsolvers.com/api/minicrossword/today'
          : 'http://localhost:5000/api/minicrossword/today';

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

        const puzzle = data.body[0];
        const clues = puzzle.clues.map((clue: any) => {
          const answer = clue.cells.map((cellIndex: number) => puzzle.cells[cellIndex].answer).join('');
          return {
            direction: clue.direction,
            number: clue.label,
            clue: clue.text[0].plain,
            answer: answer,
            hint: `${answer.length} letters`,
          };
        });

        const puzzleData = {
          date: data.publicationDate,
          clues: clues,
        };

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

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

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