import puppeteer from 'puppeteer';
import fs from 'fs';
import path from 'path';
import { pingDailyPuzzleUpdated } from '../services/indexingService';
import { launchBrowser } from "./puppeteer-launcher";

export async function generateConexoHints() {
  try {
    const browser = await launchBrowser();
    const page = await browser.newPage();

    const targetUrl = 'https://ladypuzzle.pro/conexo-hint-answer';
    console.log('[Conexo] Opening page:', targetUrl);

    try {
      await page.goto(targetUrl, {
        waitUntil: 'domcontentloaded',
        timeout: 60000, // 1 minute timeout
      });
    } catch (err) {
      console.warn('[Conexo] First attempt failed, retrying...');
      await page.goto(targetUrl, {
        waitUntil: 'domcontentloaded',
        timeout: 60000,
      });
    }

    await page.waitForSelector('button', { timeout: 15000 });

    // CLICK REVEAL BTN
    await page.evaluate(() => {
      const buttons = Array.from(document.querySelectorAll('button'));
      const revealBtn = buttons.find(btn =>
        (btn as HTMLElement).innerText.trim().toLowerCase().includes('reveal')
      );
      if (revealBtn) (revealBtn as HTMLElement).click();
    });

    await new Promise(resolve => setTimeout(resolve, 2000));

    // SCRAPE DOM
    const categories = await page.evaluate(() => {
      const groupEls = document.querySelectorAll('.rounded-md.sm\\:px-4.py-2');
      const results: any[] = [];

      groupEls.forEach(group => {
        const color = group.getAttribute('style') ?? '';
        const hintEl = group.querySelector('.btn.btn-wide span') as HTMLElement | null;
        const hint =
          hintEl && hintEl.innerText.trim() !== '?' ? hintEl.innerText.trim() : '';

        const wordButtons = group.querySelectorAll('.group-members button');
        const words: string[] = [];
        wordButtons.forEach(w => words.push((w as HTMLElement).innerText.trim()));

        results.push({
          color,
          ai_hint: hint,
          cards: words.map(w => ({ content: w })),
        });
      });

      return results;
    });

    await browser.close();

    const filteredCategories = categories.filter(c => c.cards.length > 0);
    const date = new Date().toISOString().split('T')[0];
    const conexoData = { id: Date.now(), date, categories: filteredCategories };

    const isProduction = process.env.NODE_ENV === 'production';
    const baseDir = path.join(__dirname, '..', '..', '..');
    const hintsDir = isProduction
      ? path.join(baseDir, 'nytsolvers', 'dist', 'client', 'hints', 'conexo')
      : path.join(baseDir, 'project', 'public', 'hints', 'conexo');

    if (!fs.existsSync(hintsDir)) fs.mkdirSync(hintsDir, { recursive: true });
    fs.writeFileSync(
      path.join(hintsDir, `${date}.json`),
      JSON.stringify(conexoData, null, 2)
    );

    console.log(`[Conexo] Hints generated successfully in ${hintsDir}`);

    // Trigger search engine indexing (Google Indexing API & Bing IndexNow)
    await pingDailyPuzzleUpdated('conexo-hints', date).catch((err: any) =>
      console.error('[Conexo] Error pinging search indexing:', err.message)
    );
  } catch (error) {
    console.error('❌ Error generating Conexo hints:', error);
  }
}

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