import { getFeedback, matchesFeedback } from './feedback.js';

const VOWELS = new Set([
  'a','e','i','o','u',        // Latin
  'а','е','и','о','у','ы','я',  // Cyrillic
]);

function pickBestVowelWord(pool: string[], knownVowels: Set<string>): string {
  let bestGuess = pool[0];
  let best = -1;
  for (const w of pool) {
    const newV = [...w].filter((c) => VOWELS.has(c) && !knownVowels.has(c)).length;
    const s = newV * 3 + new Set(w.split('')).size;
    if (s > best) { best = s; bestGuess = w; }
  }
  return bestGuess;
}

export function solveVowelFirst(target: string, allWords: string[], maxAttempts = 6): { attempts: number; steps: string[] } {
  let candidates = [...allWords];
  const knownVowels = new Set<string>();
  const steps: string[] = [];

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    let bestGuess: string;
    if (attempt <= 3 && knownVowels.size < 5) {
      const pool = candidates.length > 0 ? candidates : allWords;
      bestGuess = pickBestVowelWord(pool, knownVowels);
    } else {
      bestGuess = candidates[0];
    }

    const fb = getFeedback(target, bestGuess);
    steps.push(bestGuess);
    if (fb === 'ggggg') return { attempts: attempt, steps };

    for (let i = 0; i < 5; i++) { if ((fb[i] === 'g' || fb[i] === 'y') && VOWELS.has(bestGuess[i])) knownVowels.add(bestGuess[i]); }
    candidates = candidates.filter((c) => matchesFeedback(c, bestGuess, fb));
    if (candidates.length === 0) return { attempts: maxAttempts + 1, steps };
  }

  return { attempts: maxAttempts + 1, steps };
}
