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

function letterFrequency(words: string[]): Record<string, number> {
  const freq: Record<string, number> = {};
  for (const w of words) {
    const seen = new Set<string>();
    for (const ch of w) { if (!seen.has(ch)) { freq[ch] = (freq[ch] ?? 0) + 1; seen.add(ch); } }
  }
  return freq;
}

function scoreWord(word: string, freq: Record<string, number>): number {
  const seen = new Set<string>(); let s = 0;
  for (const ch of word) { if (!seen.has(ch)) { s += freq[ch] ?? 0; seen.add(ch); } }
  return s;
}

export function solveFrequency(target: string, allWords: string[], maxAttempts = 6): { attempts: number; steps: string[] } {
  let candidates = [...allWords];
  const steps: string[] = [];

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const freq = letterFrequency(candidates);
    const pool = attempt === 1 ? allWords : candidates;
    let bestGuess = pool[0]; let bestScore = -1;
    for (const g of pool) { const s = scoreWord(g, freq); if (s > bestScore) { bestScore = s; bestGuess = g; } }

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

    candidates = candidates.filter((c) => matchesFeedback(c, bestGuess, fb));
    if (candidates.length === 0) return { attempts: maxAttempts + 1, steps };
  }

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