import type { SolverStep } from '@wordle/shared';

function getFeedback(target: string, guess: string): string {
  const tu = target.toLowerCase(), gu = guess.toLowerCase();
  const counts: Record<string, number> = {};
  for (const ch of tu) counts[ch] = (counts[ch] ?? 0) + 1;
  const r: string[] = Array(5).fill('x');
  for (let i = 0; i < 5; i++) { if (gu[i] === tu[i]) { r[i] = 'g'; counts[gu[i]]--; } }
  for (let i = 0; i < 5; i++) { if (r[i] === 'g') continue; if ((counts[gu[i]] ?? 0) > 0) { r[i] = 'y'; counts[gu[i]]--; } }
  return r.join('');
}

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: SolverStep[] } {
  let candidates = [...allWords];
  const steps: SolverStep[] = [];

  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({ guess: bestGuess, colors: fb.split('') });
    if (fb === 'ggggg') return { attempts: attempt, steps };

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

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