import { readFileSync, writeFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import type { WordBank, SolverReplay } from '@wordle/shared';
import { solveEntropy } from './entropy.js';
import { solveFrequency } from './frequency.js';
import { solveVowelFirst } from './vowel-first.js';
import { solveGreedy } from './greedy.js';

const __dirname = dirname(fileURLToPath(import.meta.url));
const BANK_PATH = resolve(__dirname, '../../data/word-bank.json');
const MAX_ATTEMPTS = 6;

console.log('Loading word bank...');
const bank: WordBank = JSON.parse(readFileSync(BANK_PATH, 'utf-8'));
const allWords = bank.guessable;

console.log(`Solving ${bank.targets.length} target words with ${allWords.length} guessable words...`);

let solved = 0;
let failed = 0;
const newTargets: WordBank['targets'] = [];

for (const target of bank.targets) {
  const results = [
    { name: 'Entropy', ...solveEntropy(target.word, allWords, MAX_ATTEMPTS) },
    { name: 'Frequency', ...solveFrequency(target.word, allWords, MAX_ATTEMPTS) },
    { name: 'Vowel First', ...solveVowelFirst(target.word, allWords, MAX_ATTEMPTS) },
    { name: 'Greedy', ...solveGreedy(target.word, allWords, MAX_ATTEMPTS) },
  ];

  const passResults = results.filter((r) => r.attempts <= MAX_ATTEMPTS);

  if (passResults.length === 0) {
    console.log(`  REMOVED: ${target.word} (unsolvable by any strategy)`);
    failed++;
    continue;
  }

  const avgAttempts = passResults.reduce((s, r) => s + r.attempts, 0) / passResults.length;
  const difficulty = Math.round(avgAttempts * 100) / 100;

  const replays: SolverReplay[] = results
    .filter((r) => r.attempts <= MAX_ATTEMPTS)
    .map((r) => ({ solver: r.name, steps: r.steps }));

  newTargets.push({ ...target, difficulty, replays });

  solved++;
  if (solved % 10 === 0) console.log(`  ${solved}/${bank.targets.length}...`);
}

const newBank: WordBank = { guessable: bank.guessable, targets: newTargets };
writeFileSync(BANK_PATH, JSON.stringify(newBank, null, 2) + '\n', 'utf-8');

console.log(`\nDone! ${solved} solved, ${failed} removed. Replays stored.`);
