import { Router, Request, Response } from 'express';
import type { WordBank, CachedResult } from '@wordle/shared';
import { getDailyWordId } from '../daily-word.js';
import { getTargetWord } from '../validate.js';
import { computeReplays } from '@wordle/shared';
import { runSolverInWorker } from '../solver-pool.js';

export function createDailyRouter(wordBank: WordBank, cache: Map<number, CachedResult>): Router {
  const router = Router();

  router.get('/', (_req: Request, res: Response) => {
    const wordId = getDailyWordId(wordBank.targets.length);
    res.json({ wordId });

    // Pre-warm cache so solver replays are ready (or nearly ready) by the time
    // the player finishes their last guess.
    if (!cache.has(wordId)) {
      const target = getTargetWord(wordBank, wordId);
      if (!target) return;

      cache.set(wordId, computeReplays(target.word, wordBank.guessable));

      const targetWord = target.word;
      const guessable = wordBank.guessable;
      runSolverInWorker({ target: targetWord, allWords: guessable, mode: 'full' })
        .then((full) => { cache.set(wordId, full); })
        .catch((err) => { console.error('Solver worker failed:', err); });
    }
  });

  return router;
}
