// latimesminicrossword-generator.ts
import puppeteer from 'puppeteer';
import * as fs from 'fs';
import * as path from 'path';
import { pingDailyPuzzleUpdated } from '../services/indexingService';
import { launchBrowser } from "./puppeteer-launcher";
export async function generateLatimesMiniCrosswordHints() {
    const browser = await launchBrowser();
  const page = await browser.newPage();

  try {
    const URL = 'https://ladypuzzle.pro/la-times-mini-clues-answers-hints';
    await page.goto(URL, { waitUntil: 'networkidle2', timeout: 60000 });

    const data = await page.evaluate(() => {
      const result: { date: string; across: any[]; down: any[] } = {
        date: '',
        across: [],
        down: [],
      };

      const dateElement = document.querySelector('h1');
      if (dateElement) {
        const dateText = dateElement.textContent || '';
        const match = dateText.match(/(\w{3}, \w{3} \d{1,2}, \d{4})/);
        if (match) {
          const d = new Date(match[1]);
          result.date = d.toISOString().split('T')[0];
        }
      }

   const extractSection = (sectionTitle: string) => {
  const section: any[] = [];
  const heading = Array.from(document.querySelectorAll('h2, h3, h4, h5, h6')).find(
    (el) => el.textContent?.includes(sectionTitle)
  );

  if (heading) {
    let currentElement: Element | null = heading.nextElementSibling;
    while (currentElement && !currentElement.tagName.startsWith('H')) {
      const liElements = currentElement.querySelectorAll('li');
    liElements.forEach((li) => {
  const numberEl = li.querySelector('.clue-label');
  const clueEl = li.querySelector('.clue-text p');
  const answerEl = li.querySelector('[class*="clue-btn"][class*="hidden"]');
  const explanationEl = li.querySelector('[aria-label="clue explanation"] p');

  if (numberEl && clueEl && answerEl) {
    section.push({
      number: parseInt(numberEl.textContent || '0'),
      clue: clueEl.textContent?.trim() || '',
      answer: answerEl.textContent?.trim() || '',
      explanation: explanationEl?.textContent?.trim() || ''
    });
  }
});


      currentElement = currentElement.nextElementSibling;
    }
  }

  return section;
};


      result.across = extractSection('Across');
      result.down = extractSection('Down');

      return result;
    });

    const today = new Date();
    const dateString = today.toISOString().split('T')[0];
       const isProduction = process.env.NODE_ENV === 'production';
        const baseDir = path.join(__dirname, '..', '..', '..');
        const outputDir = isProduction
            ? path.join(baseDir, 'nytsolvers', 'dist', 'client', 'hints', 'latimesminicrossword')
            : path.join(baseDir, 'project', 'public', 'hints', 'latimesminicrossword');
    if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
    const outputPath = path.join(outputDir, `${dateString}.json`);
    fs.writeFileSync(outputPath, JSON.stringify(data, null, 2));

    console.log(`LATimesMiniCrossword hints generated for ${dateString} at ${outputPath}`);

    // Trigger search engine indexing (Google Indexing API & Bing IndexNow)
    await pingDailyPuzzleUpdated('la-times-mini-hints', dateString).catch((err: any) =>
      console.error('[LA Times Mini] Error pinging search indexing:', err.message)
    );
  } catch (error) {
    console.error('Error generating LATimesMiniCrossword hints:', error);
  } finally {
    await browser.close();
  }
}

if (require.main === module) {
  generateLatimesMiniCrosswordHints();
}
