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

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

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    let bestGuess = candidates[0];
    let bestEntropy = Infinity;
    const pool = attempt === 1 ? allWords : candidates;

    for (const guess of pool) {
      const buckets: Map<string, number> = new Map();
      for (const c of candidates) {
        const fb = getFeedback(c, guess);
        buckets.set(fb, (buckets.get(fb) ?? 0) + 1);
      }
      let expected = 0;
      for (const count of buckets.values()) expected += (count / candidates.length) * count;
      if (expected < bestEntropy) { bestEntropy = expected; bestGuess = guess; }
    }

    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 };
}
