import { readFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import type { WordBank } from '@wordle/shared';
import { solveEntropy, solveFrequency, solveVowelFirst, solveGreedy } from '@wordle/shared';

const __dirname = dirname(fileURLToPath(import.meta.url));
const MAX_ATTEMPTS = 6;

const SOLVERS = [
  { name: 'Entropy', fn: solveEntropy },
  { name: 'Frequency', fn: solveFrequency },
  { name: 'Vowel First', fn: solveVowelFirst },
  { name: 'Greedy', fn: solveGreedy },
];

function validateBank(bankPath: string) {
  console.log(`\n=== ${bankPath} ===`);
  const bank: WordBank = JSON.parse(readFileSync(bankPath, 'utf-8'));
  const allWords = bank.guessable;

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

  let ok = 0, unsolvable = 0;
  for (const target of bank.targets) {
    const results = SOLVERS.map((s) => ({
      name: s.name,
      ...s.fn(target.word, allWords, MAX_ATTEMPTS),
    }));

    const passResults = results.filter((r) => r.attempts <= MAX_ATTEMPTS);
    if (passResults.length === 0) {
      console.log(`  UNSOLVABLE: ${target.word}`);
      unsolvable++;
    } else {
      ok++;
    }
    if ((ok + unsolvable) % 10 === 0) console.log(`  ${ok + unsolvable}/${bank.targets.length}...`);
  }

  console.log(`Done! ${ok} solvable, ${unsolvable} unsolvable.`);
}

const DATA_DIR = resolve(__dirname, '../../data');
validateBank(resolve(DATA_DIR, 'word-bank.json'));
validateBank(resolve(DATA_DIR, 'word-bank-ru.json'));
console.log('\nAll banks validated.');
