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

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

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

        const response = await axios.get(`${API_BASE_URL}/api/strands?date=${date}`);
        const data = response.data;

        const puzzleDate = new Date(data.printDate).toISOString().split('T')[0];
        const filePath = path.join(hintsDir, `${puzzleDate}.json`);

        const puzzleData = {
          date: puzzleDate,
          number: data.id,
          theme: data.clue,
          hint: data.clue,
          spangram: data.spangram,
          spangramHint: `The spangram is a word related to '${data.clue}'.`,
          words: data.themeWords,
          explanation: 'All words are related to the theme of going the distance.',
          startingBoard: data.startingBoard
        };

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

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

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