import { Router, Request, Response } from 'express';
import type { WordBank, CachedResult } from '@wordle/shared';
import { selectPlayAgainWord } from '../play-again.js';
import { computeReplays } from '@wordle/shared';
import { runSolverInWorker } from '../solver-pool.js';

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

  router.post('/', (req: Request, res: Response) => {
    const { skillMetric } = req.body ?? {};

    if (typeof skillMetric !== 'number') {
      res.status(400).json({ error: 'skillMetric (number) required' });
      return;
    }

    const target = selectPlayAgainWord(wordBank.targets, skillMetric, cache);
    res.json({ wordId: target.id });

    // Pre-warm cache so solver replays are ready (or nearly ready) by the time
    // the player finishes their last guess.
    if (!cache.has(target.id)) {
      cache.set(target.id, computeReplays(target.word, wordBank.guessable));

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

  return router;
}
