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

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

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

        const wordleResponse = await axios.get(API_URL);
        const responseData = wordleResponse.data;

        if (responseData && responseData.solution && typeof responseData.solution.solution === 'string') {
            const { solution, id, print_date } = responseData.solution;
            const puzzleDate = print_date || date;
            const puzzleData = {
                date: puzzleDate,
                number: id,
                answer: solution,
            };

            const targetDirs = [
              path.join(baseDir, 'project', 'public', 'hints', 'wordle'),
              path.join(baseDir, 'project', 'dist', 'client', 'hints', 'wordle'),
              path.join(baseDir, 'nytsolvers', 'dist', 'client', 'hints', 'wordle'),
            ];

            for (const dir of targetDirs) {
              try {
                if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
                const filePath = path.join(dir, `${puzzleDate}.json`);
                fs.writeFileSync(filePath, JSON.stringify(puzzleData, null, 2), 'utf8');
                console.log(`Successfully generated Wordle hints: ${filePath}`);
              } catch (e) {
                // directory not on this host
              }
            }
            // Trigger search engine indexing (Google Indexing API & Bing IndexNow)
            await pingDailyPuzzleUpdated('wordle-hints', puzzleDate).catch((err: any) =>
              console.error('[Wordle] Error pinging search indexing:', err.message)
            );
        } else {
            console.error('Invalid API response structure for Wordle');
        }

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