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

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

    try {
        const url = 'https://www.nytimes.com/puzzles/letter-boxed';
        const userAgent = 'Mozilla/5.0'; // Mimic browser user agent

        const response = await axios.get(url, { headers: { 'User-Agent': userAgent } });
        const html = response.data;

        const searchString = 'window.gameData = ';
        const startIndex = html.indexOf(searchString);

        if (startIndex === -1) {
            throw new Error('Game data script not found in HTML');
        }

        const jsonStartIndex = html.indexOf('{', startIndex);
        if (jsonStartIndex === -1) {
            throw new Error('Game data JSON object start not found');
        }

        let openBraces = 1;
        let jsonEndIndex = -1;

        for (let i = jsonStartIndex + 1; i < html.length; i++) {
            if (html[i] === '{') {
                openBraces++;
            } else if (html[i] === '}') {
                openBraces--;
            }

            if (openBraces === 0) {
                jsonEndIndex = i + 1;
                break;
            }
        }

        if (jsonEndIndex === -1) {
            throw new Error('Could not find the end of the game data JSON object.');
        }

        const gameDataString = html.substring(jsonStartIndex, jsonEndIndex);
        const todaysMetadata = JSON.parse(gameDataString);

        // Use printDate from metadata if available
        const puzzleDate = todaysMetadata.printDate || date;
        const filePath = path.join(hintsDir, `${puzzleDate}.json`);

        const sides = todaysMetadata.sides ?? [];
        const ourSolution = todaysMetadata.ourSolution ?? [];

        const puzzleData = {
          date: puzzleDate,
          number: todaysMetadata.id,
          letters: {
            top: sides[0]?.split('') || [],
            right: sides[1]?.split('') || [],
            bottom: sides[2]?.split('') || [],
            left: sides[3]?.split('') || [],
          },
          ourSolution: ourSolution,
        };

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

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

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