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

export function solveGreedy(target: string, allWords: string[], maxAttempts = 6): { attempts: number; steps: string[] } {
  let candidates = [...allWords];
  const STARTERS = ['crane','slate','arise','stare'];
  const steps: string[] = [];

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const guess = attempt === 1 ? (STARTERS.find((w) => allWords.includes(w)) ?? allWords[0]) : candidates[0];
    const fb = getFeedback(target, guess);
    steps.push(guess);
    if (fb === 'ggggg') return { attempts: attempt, steps };

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

    if (attempt < maxAttempts) {
      const greens: number[] = [];
      for (let i = 0; i < 5; i++) if (fb[i] === 'g') greens.push(i);
      if (greens.length > 0) {
        candidates.sort((a, b) => {
          let am = 0, bm = 0;
          for (const p of greens) { if (a[p] === guess[p]) am++; if (b[p] === guess[p]) bm++; }
          return bm - am;
        });
      }
    }
  }

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